0% found this document useful (0 votes)
40 views

Unit 1

Uploaded by

dhanu.srii.002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Unit 1

Uploaded by

dhanu.srii.002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 143

U23IT303-

OBJECT
ORIENETED
PROGRAMMING
IN C++
UNIT I
OBJECT ORIENTED CONCEPTS

• Introduction to Object Oriented Programming and C++: Object oriented concepts


and its characteristics: abstraction, encapsulation, inheritance, and polymorphism.
History of C++ - Structure of C++-Applications of C++- Tokens- Keywords-
Identifiers-Basic data types- Derived data types- Symbolic constants- Dynamic
initialization -Reference variables- Scope resolution operator-Type modifiers- Type
casting.

• C++ Operators and control statements- Input and output statements- Function
Prototyping-Function components- Passing parameters - call by reference, return by
reference- Inline function- Default arguments - Overloaded function- Introduction
to friend function.
UNIT II
CLASSES AND OBJECTS, CONSTRUCTORS AND DESTRUCTORS

• Classes and Objects: Class specification- Member function definition- Nested


member function- Access qualifiers- Static data members and member functions -
Instance creation- Array of objects- Dynamic objects-Static Objects- Objects as
arguments- Returning objects.

• Constructors and Destructors: Constructors – Parameterized constructors-


Overloaded Constructors- Constructors with default arguments-Copy constructors-
Dynamic constructors-Dynamic initialization using constructors- Destructors.
UNIT III
OPERATOR OVERLOADING AND TEMPLATES

• Operator Overloading: Operator function – Overloading unary and binary operator-


Overloading binary operator using friend function - Type Conversion.

• Generic Programming with Templates: Introduction, class templates – class


templates with multiple parameters - Function templates, Function templates with
multiple parameters- overloading of function templates, Member function
Templates, Non-Type Template Arguments- Inheritance of class template.
UNIT IV
INHERITANCE AND VIRTUAL FUNCTIONS

• Inheritance: Defining Derived classes- Single Inheritance- Protected Data with


private inheritance- Multiple Inheritance- Multi level inheritance- Hierarchical
Inheritance- Hybrid Inheritance-Multipath inheritance- Virtual Base Classes-
Abstract classes -Constructors in derived class- Member Classes

• Virtual Function: Definition – Runtime Polymorphism – Array of pointers to base


class – virtual functions - Pure virtual functions – Virtual Destructors.
UNIT V
STREAMS AND EXCEPTION HANDLING

• Streams: Streams in C++- Stream classes- Formatted and unformatted data-


Manipulators- User defined manipulators- File streams-File pointer and
manipulation-File open and close- Sequential and random access-Name Space.

• Exception Handling: Principle of exception handling-Exception handling


mechanism, multiple catch, nested try, rethrowing the exception – specifying
exceptions.
TEXT BOOKS

• Robert Lafore, “Object-Oriented Programming in C++” Pearson Education,


4 Edition, 2008.
• K R Venugopal, Rajkumar Buyya “Mastering C++” Tata McGraw Hill, New
Delhi, Second edition 2015.
Course Outcomes
Why Programming language?
History of Programming Language.
Types of
Programmi
ng
Language
Procedural Oriented Programming(PoP) Language

• Procedural Programming involves writing down a list of instructions


to tell the computer what it should do step-by-step to finish the task.
• Procedural code is the one that directly instructs a device on how to
finish a task in logical steps.
• This paradigm uses a linear top-down approach .
• Treats data and procedures as two different entities.
• Procedural Programming divides the program into procedures, which
are also known as routines or functions, simply containing a series of
steps to be carried out.
Structure , Handling of Data & Functions of POP
Object-Oriented Programming (OOP) Language

• Object-oriented programming (OOP) is defined as a programming


paradigm built on the concept of objects.
• Object-oriented programming is based on the concept of objects.
• Objects are defined, each with its own properties or attributes.Each
object can also contain its own procedures or methods.
• Object-oriented languages is to combine into a single unit both data
and the functions that operate on that data. Such a unit is called an
object.
• Data encapsulation and data hiding are key terms in the description
of object-oriented languages.
Structure , Handling of Data & Functions of OOP :
POP vs OOP

Procedural Oriented Programming Object Oriented Programming


In procedural programming, program is In object oriented programming,
divided into small parts program is divided into small parts
called functions. called objects.
Procedural programming follows top Object oriented programming
down approach. follows bottom up approach.
Object oriented programming have
There is no access specifier in
access specifiers like private, public,
procedural programming.
protected etc.
Adding new data and function is not
Adding new data and function is easy.
easy.
POP vs OOP

Procedural programming does not have


Object oriented programming provides
any proper way for hiding data so it
data hiding so it is more secure.
is less secure.
In procedural programming, overloading Overloading is possible in object-
is not possible. oriented programming.
In procedural programming, function is In object-oriented programming, data is
more important than data. more important than function.
Procedural programming is based Object oriented programming is based
on unreal world. on real world.
Examples: C, FORTRAN, Pascal, Basic
Examples: C++, Java, Python, C# etc.
etc.
C Programs

• Write a C Program to display hello world message.


• Write a C Program to add two numbers.
• Write a C function to display Greeting message.
• Write a Structure program to display name and roll number of
student.
OOPS
Concepts
Class

• The building block of C++ that leads to Object-Oriented


programming is a Class.
• It is a user-defined data type, which holds its own data
members and member functions, which can be accessed
and used by creating an instance of that class.
• A class is like a blueprint for an object.
Object

• An object is any real-time entity with some properties and behaviors.


• An Object is an instance of a Class.
• The object is the basic unit of the object-oriented programming paradigm.
• When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
• When a program is executed the objects interact by sending messages to one
another.
• Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code
Encapsulation

•Encapsulation means encapsulating (binding or wrapping) code and data into a


single unit.
• Encapsulation means placing the data and the functions that work on that data
in a single place.
Abstraction

•Abstraction means avoiding unnecessary and irrelevant information and only


showing the specific details of what users want to see.
•Refers to showing only the most relevant information while hiding the details.
Polymorphism

•Polymorphism means taking more than one form.


•Refers to showing only the most relevant information while hiding the details.
Inheritance

•Inheritance is the process of acquiring properties from one object to another


object.
•Inheritance is the process of deriving a new class from an existing class where
the members of the existing class are extended to the newly derived class..
History of C++

• Developed by Danish computer scientist Bjarne Stroustrup in 1979 at Bell


Laboratories USA.
• The C++ language was initially designed as an extension of the C language,
which was widely used in system programming and Unix-based OS.
• C++ was initially known as “C with classes, ” and was renamed C++ in
1983. ++ is shorthand for adding one to variety in programming; therefore
C++ roughly means that “one higher than C.”
Bjarne Stroustrup
Simple Hello World Program

#include<iostream>
using namespace std;
int main()
{
cout<<“Hello World”;
return 0;
Output:
} Hello World
Structure of
C++ (PoP)
1. Header File
• The header files contain the definition of the functions and macros.
• They are defined on the top of the C++ program.
• The #include <iostream> statement to tell the compiler to
include an iostream header file library which stores the definition
of the cin and cout standard input/output streams that we have
used for input and output.
• #include is a preprocessor directive using which we import
header files.
• Syntax:
#include <library_name>
2. Namespace
• A namespace in C++ is used to provide a scope or a region where we
define identifiers.
• It is used to avoid name conflicts between two identifiers as only unique
names can be used as identifiers.
• In line #2, we have used the using namespace std statement for
specifying that we will be the standard namespace where all the standard
library functions are defined.
• Syntax:
using namespace std;
3. Main Function
• Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task.
• A function definition also contains information about its return type and
parameters.
• In line #3, we defined the main function as int main(). The main function
is the most important part of any C++ program. The program execution
always starts from the main function.
• All the other functions are called from the main function. In C++, the main
function is required to return some value indicating the execution status.
• Syntax:
int main()
{
... code ....
return 0;
}
4. Blocks
• Blocks are the group of statements that are enclosed within { } braces.
• They define the scope of the identifiers and are generally used to enclose
the body of functions and control statements.
• The body of the main function is from line #4 to line #9 enclosed within
{ }.
• Syntax:
{
Statements;
}
5. Semicolons
• It is used to terminate each line of the statement of the program.
• When the compiler sees this semicolon, it terminates the operation of that
line and moves to the next line.
• Syntax:
any_statement ;
6. Identifiers
• Use identifiers for the naming of variables, functions, and other
user-defined data types.
• An identifier may consist of uppercase and lowercase
alphabetical characters, underscore, and digits.
• The first letter must be an underscore or an alphabet.
• Example:int num1 = 24; //num1 is identifiers
7. Keywords
• In the C++ programming language, there are some reserved words that
are used for some special meaning in the C++ program.
• It can’t be used for identifiers.
• There are total 95 keywords in C++.
• Example:
• int void if while for auto bool break
Structure of
C++ (ooP)
1. Class
• A class is a template of an object. It is a user-defined data type.
• A class has its own attributes (data members) and behavior (member
functions).
• The first letter of the class name is always capitalized & use the class
keyword for creating the class.
• Syntax:
class class_name
{
// class body
};
2. Data Members & Member Functions
• The attributes or data in the class are defined by the data members & the
functions that work on these data members are called the member
functions.
• There is a keyword here public that is access modifiers. The
access modifier decides who has access to these data
members & member functions.
• public access modifier means these data members & member
functions can get access by anyone.
3. Object
• The object is an instance of a class. The class itself is just a template that is
not allocated any memory.
• To use the data and methods defined in the class, we have to create an
object of that class.
• Use dot operator ( . ) for accessing data and methods of an object.
• Syntax:
class_name object_name;
Applications
of C++
Tokens
• The smallest individual units in program are known as tokens. C++ has
the following tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
Identifiers:
• Identifiers are names given to various entries, such as variables,
structures, and functions. Also, identifier names must be unique as
these entities are used in program execution.
• int student_age = 25; // student_age is an integer variable or identifier
• Naming style of Identifiers:
• Must begin with an alphabet character (A-Z or a-z) or an
underscore(_).
• An Identifier consists of characters, numbers and underscore.
• Blank space and Special characters should not be used in identifier
declaration.
• Not exceed 31 characters.
• Case sensitive.
• Can't use keyword as identifiers.
Valid
Identifiers Invalid Identifiers
name
123name
NAME
%name
_Name
stud name
Name_
any keywords like
Name123
int, string, etc.
_name_
Keywords
• Keywords are reserved words with
fixed meanings that cannot be
changed.
• The meaning and working of these
keywords are already known to the
compiler.
• C++ has more numbers of
keywords than C, and those extra
ones have unique working
capabilities.
• auto: declares a variable as 'automatic' type. • else: Executes a block of code when an if
• break: used inside loop for sudden termination condition is false.
if required. • enum: Declares an enumeration.
• case: used within 'switch' statement where • explicit: Specifies that a constructor or
redirecting occurs on choice. conversion function should not be implicitly
• default: used within 'switch' statement where invoked.
redirecting occurs on wrong choice. • extern: Declares that a variable or function is
• char: used to declare a character type variable. defined externally.
• class: used to declare a class type variable. • float: Declares a single-precision floating-point
type.
• const: declares a constant variable which cannot
be changed. • for: Starts a for loop.
• continue: Jumps to the next iteration within a • friend: Declares a function or class as a friend,
loop. allowing it to access private members of
another class.
• delete: Deallocates memory for an object created
with new. • goto: Transfers control to a labeled statement.
• do: Starts a do-while loop. • if: Specifies a conditional statement.
• double: Declares a double-precision floating-
point type.
• inline: Suggests to the compiler to perform in- • return: Returns a value from a function.
lining, i.e., to insert the complete body of the • short: Declares a short integer type.
function at the point of the call.
• signed: Declares a signed integer type.
• int: Declares an integer type.
• sizeof: Returns the size, in bytes, of a type or
• long: Declares a long integer type.
object.
• namespace: Declares a scope that contains a •
static: Specifies that a variable or function is
set of identifiers. static, meaning it retains its value or scope
• new: Allocates memory for an object or an throughout the program's execution.
array. • struct: Declares a structure.
• operator: Declares an operator function. • switch: Starts a switch statement.
• private: Specifies that class members are •
template: Specifies a template for generic
accessible only within the class. programming.
• protected: Specifies that class members are •
this: A pointer that points to the current object.
accessible within the class and its subclasses.
• throw: Throws an exception.
• public: Specifies that class members are
accessible from outside the class. • try: Specifies a block of code to be tested for
exceptions.
• register: Suggests to the compiler to store the
variable in a register for faster access. • typedef: Defines a new type using an existing
type.
• union: A data structure that allows storing different types of data in the same
memory location is called union.
• unsigned: It declares an unsigned integer type.
• using: It introduces a name from a namespace into the current scope.
• virtual: It specifies that a function can be overridden in a derived class.
• void: Means that a function or a pointer does not return a value
• volatile: It means that a variable can be changed outside of the program.
• Operators
• C++ operator is a symbol that
is used to perform
mathematical or logical
manipulations.
• Other Operators in C++

Operator Example Description


sizeof sizeof(int); // 4 It returns the size of datatype
&num //address of Used to represent the memory address of
&
num variable
Used to access the members like structure
. player.score = 91;
variables or class members
Used with the pointers to access the class
-> ptr->score = 32;
or structure variables
<< cout << "Hello"; Used to print the output on command line

>> cin >> num; Used to take input from command line
Constants
• Constants are like a variable,
except that their value never
changes during execution once
defined.
• There are two common types of
constants in C++
• Literal constant
• Symbolic constant
• A symbolic constant is a name given to values that cannot be changed. A
constant must be initialized.
• After a constant is initialized, its value cannot be changed.
• Symbolic constants are used to represent a value that is frequently used in a
program.
• Symbolic constants can be declared in two ways:
• Const Qualifier: Const data-type identifier = value;
• Example: Const int N = 100;
• Define Directive: #define identifier value
• Example: # define PI 3.1411596
Strings
• A string in C++ is an object that represents a sequence of characters.
• Strings in C++ are a part of the standard string class
(std::string)
• Syntax:
• string object_name= value;
• charAt(index) used to access the character of string.
Data types:
• A data type defines the type and the set of operations that can be
performed on the data.
• The data is given as an input to the program. According to the
program's set of instructions, data is processed and then output is
returned on the screen.
• Before designing the actual program data, its type and operations
performed on it are defined and used to process the data.
• At the start of the program, the type of each data value is identified.
Integer
Character
• Characters are stored by using character data type.
• Char is used to representing character data type.
• It normally requires 1 byte of memory.
• As each character is assigned by a unique ASCII code which is an
integer so that’s why characters are included in integral data type.
• When we store a character in memory, we actually store a unique
numeric code associated with that character in memory.
• And when the computer is instructed to print characters, it basically
prints characters associated with the numeric code.
void
• The type void normally used for:
1) To specify the return type of function when it is not returning any
value.
2) To indicate an empty argument list to a function.
Example:
Void function(void);
Another interesting use of void is in the declaration of genetic
pointer
Example:
Void *gp;
float
• A float data type is used to store real numbers or large numbers with a fractional
component like 1.0,14.01,23.45,-21.560,191.123456, etc. The part after the decimal is
known as its fractional component.
• 1-bit for the sign, 8-bit for exponent, 23-bit for the value or mantissa.The size of a
float is 4-bytes(32 bit)
• why the name ‘float’?
• Decimal is referred to as floating-point because we can observe from above that decimal
supports a variable number of digits before and after it, which means decimal point can float
between the numbers. Thus the name float data type comes from the floating-point.
• Syntax:
• float variable_name;
• Example:
• float a;
• float a=3.5;
double
• Double data type in C++ is a versatile data type that can represent any numerical value in the
compiler, including decimal values.
• There are two types of double data types in C++: whole numbers as well as fractional numbers with
values.
• It takes 8byte of Memory.
• The compiler in C++, by default, treats every value as a double and implicitly performs a type
conversion between different data types.
• Syntax:
• double variable_name;
• Example:
• double var_1, var_2, var_3;
• double var1 = 5.999999;
• double var2 = 5.0;
• double var3 = 5;
• double var4 = -5.0000;
User Defined Data
Types struct Person {
string first_name;
string last_name;
int age;
STRUCTERS
float salary;
• A structure is a user-defined data type in C/C+ // member function to display information
+. A structure creates a data type that can be
used to group items of possibly different types
about the person
into a single type. void displayInfo()
{
• In C++, structures can also have member
functions. cout << "First Name: " << first_name << endl;
cout << "Last Name: " << last_name << endl;
• Syntax:
cout << "Age: " << age << endl;
struct structure_name
cout << "Salary: " << salary << endl;
{
}
Data elements
};
Member functions
};
union Person {
Union string first_name;
• Union is a datatype defined by the string last_name;
user, and all the different members int age;
of the union have the same memory float salary;
location.
// member function to display information
• The member of the union, which about the person
occupies the largest memory,
decides the union’s size. void displayInfo()
• In C++, structures can also have {
member functions. cout << "First Name: " << first_name << endl;
Syntax: cout << "Last Name: " << last_name << endl;
union union_name cout << "Age: " << age << endl;
{ cout << "Salary: " << salary << endl;
data elements }
Member functions };
};
CLASSES
• C++ also permits us to define another
user defined data type known as class
which can be used just like any other
basic data type to declare a variable. The
class variables are known as objects,
which are the central focus of oops.
Syntax :
class classname
{
Data members
Function members
};
Enum:
• An enumerated data type is another #include <iostream>
user defined type which provides a way using namespace std;
for attaching names to number, these by
increasing comprehensibility of the enum week { Sunday, Monday, Tuesday,
code. Wednesday, Thursday, Friday, Saturday };
• The enum keyword automatically
enumerates a list of words by assigning int main()
them values 0,1,2 and soon. This facility {
provides an alternative means for week today;
creating symbolic. today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Array
• An array is a variable which can store multiple values of same data type at a time
or Collection of similar data items stored in continuous memory locations with
single name.
int a[3];

the compiler allocates total 6


bytes of continuous memory
locations with single name 'a’.

a[1]=100;
• Arrays are classified into two types. They are as follows...
Single Dimensional Array / One Dimensional Array
• In c programming language, single dimensional arrays are used to store list of values of same
datatype. single dimensional arrays are used to store a row of values.
• Syntax: datatype arrayName [ size ] ; or
datatype arrayName [ ] = {value1, value2, ...} ;
• Example: int rollNumbers [60] ;
• int marks [] = { 89, 90, 76, 78, 98, 86 } ;
• char studentName [] = "btechsmartclass" ;
Multi Dimensional Array
• An array of arrays is called as multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array
can be of two dimensional array or three dimensional array or four dimensional array or more...
• Syntax:datatype arrayName [ rowSize ] [ columnSize ] ;
• Example: int matrix_A [2][3] ;
• int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
int i, *ptr; float f;
Pointer i = 10; // Allowed
• A pointer is a special type of variable used to store ptr = &i; // Allowed
the address of another variable of same data type. ptr = &f; // Not allowed - Data type
mismatch
• The pointer variable may be of any data type, but
ptr = 65524; // Not allowed - Dirct value
every pointer can store the address of same data
type variable only. That means, an integer pointer not accepted
can store only integer variable address and float
pointer can store only float variable address.
• Creating a pointer
• Syntax: data_type *variable_name; or data_type*
variable_name;
• Example: int *ptr; or int* ptr;
• To access Value:
int i, *ptr;
i = 10;
ptr = &i;
cout << "Value of i = " << *ptr << endl;
DECLARATION OF VARIABLES:
• In ANSI C all the variable which is to be used in programs must be
declared at the beginning of the program .
• But in C++ we can declare the variables any whose in the program
where it requires .
• This makes the program much easier to write and reduces the errors
that may be caused by having to scan back and forth. It also makes the
program easier to understand because the variables are declared in the
context of their use.
int main( )
{
float x,average;
float sum=0; P.T.O 24
for(int i=1;i<5;i++)
{
cin>>x;
sum=sum+x
}
float average;
average=sum/x;
cout<<average;
}
REFERENCE VARIABLES:
• C++interfaces a new kind of variable known as the reference variable.
• A references variable provides an alias.(alternative name) for a
previously defined variable.
• A reference variable is created as follows:
Syntax: Datatype & reference–name=variable name;
• For example ,if we make the variable sum a reference to the variable
total, then sum and total can be used interchangeably to represent the
variable.
float total=1500;
float &sum=total;
• A reference variable must be initialized at the time of declaration .
SCOPE RESOLUTION OPERATOR:
• Like C,C++ is also a block-structured language. Block -structured
language.
• Blocks and scopes can be used in constructing programs.
• We know same variables can be declared in different block
because the variables declared in blocks are local to that function.
• Syntax: : : variable –name;
#include <iostrcam.h> cout<<”\n we are in outer
int m=10; block \n”;
main() cout<<"m="<<m<<endl;
{ cout<<":: m="<<:: m<<endl;
int m=20; }
{
int k=m;
int m=30;
cout<<”we are in inner block”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
Type Modifiers
• There are some modifiers in C++ that allow us to alter the meaning of base types
like int, char, and double. The modifiers are as follows:
• signed - Used for both positive and negative values
• unsigned - Used for only positive values
• long - Used to increase the size of data-types
• short - Used to reduce the size of data-types
• Link: https://www.scaler.com/topics/cpp/modifiers-in-cpp/
Type Casting
• In a c programming language, the data conversion is performed in two different methods as follows.
• Type Conversion
• Type Casting
• Type Conversion
• The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
• Sometimes type conversion is also called implicit type conversion. The implicit type conversion
is automatically performed by the compiler.
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i
• Typecasting
• Typecasting is also called an explicit type conversion. Compiler converts data
from one data type to another data type implicitly. When compiler converts
implicitly, there may be a data loss.
• In such a case, we convert the data from one data type to another data type using
explicit type conversion. To perform this we use the unary cast operator.
• Syntax: (TargetDatatype) DataValue
• Example: float average=(float)500/5;
Operators
• In C++ language, the operators are classified as follows.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Increment and Decrement Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators
• Scope Resolution Operators
• Other Operators
Arithmetic Operators (+, -, *, /, %)
• The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo. The following table provides information about arithmetic
operators.
Relational Operators (<, >, <=, >=, ==, !=)
• The relational operators are the symbols that are used to compare two values. That
means the relational operators are used to check the relationship between two
values. Every relational operator has two results TRUE or FALSE.
Logical Operators (&&, ||, !)
• The logical operators are the symbols that are used to
combine multiple conditions into one condition.
Increment & Decrement Operators
(++ & --)
• The increment and decrement operators are called unary operators because both
need only one operand.
• The increment operators adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand.

• The increment and decrement operators are used infront of the operand (++a) or
after the operand (a++).
• If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-
decrement.
Assignment Operators (=, +=, -=,
*=, /=, %=)
• The assignment operators are used to assign right-hand
side value (Rvalue) to the left-hand side variable
(Lvalue). The assignment operator is used in different
variants along with arithmetic operators.
Bitwise Operators (&, |, ^, ~, >>,
<<)
• The bitwise operators are used to perform bit-level operations in the c++ programming
language. When we use the bitwise operators, the operations are performed based on the
binary values.
Conditional Operator (?:)
• The conditional operator is also called a ternary operator because it
requires three operands. This operator is used for decision making. In
this operator, first we verify a condition, then we perform one
operation out of the two operations based on the condition result. If
the condition is TRUE the first option is performed, if the condition is
FALSE the second option is performed. The conditional operator is
used with the following syntax.
• Syntax: Condition ? TRUE Part : FALSE Part;
• Example code: A = (10<15)? 100 : 200; // ⇒ A value is 100
Other Operators
• Scope Resolution Operator (: :)
• sizeof operator: sizeof(variableName);
• Pointer operator (*)
• Comma operator (,)
• Dot operator (.)
The operators are also classified based on the number of operands required by the
operator.
Unary Operators
- Requires only one operand like ++ and --.Binary Operators
- Requires two operands like +, *, ==, ||, >>, etc.Ternary Operators
- Requires three operands like conditional operator.
Control Flow Statement Types
if else…
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Switch Statements
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the
Weekend";
}
For Loop
// noinit.cpp: for loop without initialization
and updation
#include <iostream>
using namespace std;
int main()
{
int i = 1;
for( ; i<=10; )
{
cout << i*5 <<" " ;
++i;
}
}
Break
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
While Loops
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Do/While Loop
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Continue
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Goto
for (int i = 0; i < 10; i++) {
if (i == 4) {
goto final;
}
cout << i << "\n";
Final:
break;
}
Input and output statements
• Header files available in C++ for
Input/Output operations are:

• iostream: This header file contains


definitions of objects like cin, cout, cerr,
etc.
• iomanip: The methods declared in these
files are used for manipulating streams.
This file contains definitions of setw,
setprecision, etc.
• fstream: This header file mainly describes
the file stream.
iostream
iomanip
fstream
In order to open a file with a stream
object we use its member
function open:

open (filename, mode);


Function
Functions
• This process of splitting a large program into small
manageable tasks and designing them independently is
popularly called modular programming or divide-
and-conquer technique.
• A repeated group of instructions in a program can be
organized as a function.
FUNCTION COMPONENTS

There are five elements involved in using a function:


the function prototype/ declaration, the function
call, the function parameters, function definition
and the function return.
Function Prototype
Function Prototype
• A function prototype is a declaration in C and C++ of a
function, its name, parameters and return type before
its actual declaration.
Function Definition
• The function itself is referred to as function definition.
The first line of the function definition is known as
function declarator and is followed by the function
body.
Function Call
• A function call is specified by the function name
followed by the arguments enclosed in parentheses and
terminated by a semicolon.

c = max( a, b ); // function call


Function Parameters
• The parameters specified in the function
call are known as actual parameters and
those specified in the function declarator
are known as formal parameters.
E.g:
#include<iostream> Func. definition int cal_age(int year) {
Using namespace std; --------
Int cal_age(int year); ----------
Func. Prototype/Declaration
}
Int main(){
---------
---------
C= age(a); }Func. call
Function Return
• Functions can be grouped into two categories: functions
that do not have a return value(void functions) and
functions that have a return value.
Default Arguments
Default Arguments
• A default argument is a value provided in a function
declaration that is automatically assigned by the
compiler if the calling function doesn’t provide a value
for the argument.
• In case any value is passed, the default value is
overridden.
//default.cpp
#include <iostream>
using namespace std;

int sum(int x, int y, int z = 0, int w = 0)


{
return (x + y + z + w);
}

int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Parameter Passing
Parameter Passing
• Parameter passing is a mechanism for communication
of data and information between the calling
function(caller) and the called function(callee).
• Three types of parameter-passing schemes:
• Pass by Value
• Pass by References
• Pass by Address or pass by Pointer
• The formal parameters are those specified in the
function declaration and function definition.
• The actual parameters are those specified in the
function call.
Pass by Value
• The default mechanism of parameter passing is called
pass by value.
• This method is also called as call by value.
//value.cpp
#include <iostream>
using namespace std;

void fun(int a)
{
a=20;
}
int main()
{
int a =10;
fun(a);

cout<<"Value of A: "<<a<<endl;
return 0;
}
Pass by Reference
• In case of pass by reference, we pass argument to the
function at calling position.
• That reflects changes into parent function.
• Scope of modification is reflected in calling function
also.
• This method is also called as call by references.
//reference.cpp
#include <iostream>
using namespace std;

void fun(int &b)


{
b=20;
}
int main()
{
int a =10;
fun(a);

cout<<"Value of A: "<<a<<endl;
return 0;
}
Pass by Address or pass by Pointer
• In case of pass by reference, we pass argument to the
function at calling position.
• That reflects changes into parent function.
• Scope of modification is reflected in calling function
also.
//address.cpp
#include <iostream>
using namespace std;
void fun(int *b)
{
*b=20;
}
int main()
{
int a =10;

fun(&a);
cout<<"Value of A: "<<a<<endl;

return 0;
}
Inline Function
Inline Function
• Execution of a normal function call involves
the operation of saving actual parameter
and function return address onto the stack
followed by a call to the function.
• On return, the stack must be cleaned to
restore the original status.
• Inline functions are those whose function
body is inserted in place of the function-call
statement during the compilation process.
• Programs with inline functions execute
faster than programs containing normal
functions(non inline)
// square.cpp: square of a number using inline
function
#include<iostream>
inline int sqr( int num )
{
return num*num;
}
int main()
{
float n;
cout<< "Enter a number: ";
cin >> n;
cout << "Its Square = " << sqr(n) << endl;
cout << "sqr( 10 ) = " << sqr( 10 );
}
FUNCTION
OVERLOADING
Function Polymorphism or Function
Overloading
• Assigning one or more function bodies to the same
name is known as a function overloading or function-
name overloading.
// Show.cpp: display void show( char *val )
different types of {
information with same
function cout << "String: " << val
<< endl;
#include <iostream>
}
using namespace std;
int main ()
void show( int val )
{
{
show( 420);
cout << "Integer: " << val
<< endl;
} show(3.1415 );
void show( double val )
{ show("Hello World\n!");
cout << "Double: " << val }
<< endl;
}

You might also like