[go: up one dir, main page]

0% found this document useful (0 votes)
11 views115 pages

CH 4-Constructor & Destructor

Chapter 4 discusses constructors and destructors in C++, which are special member functions for object initialization and destruction, respectively. It also covers the importance of functions in programming, their structure, advantages, and the concept of static members and functions, which persist throughout the program's execution. Additionally, it introduces call by reference, allowing functions to modify the actual parameters directly.

Uploaded by

GK Vines
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views115 pages

CH 4-Constructor & Destructor

Chapter 4 discusses constructors and destructors in C++, which are special member functions for object initialization and destruction, respectively. It also covers the importance of functions in programming, their structure, advantages, and the concept of static members and functions, which persist throughout the program's execution. Additionally, it introduces call by reference, allowing functions to modify the actual parameters directly.

Uploaded by

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

CH.

4: Constructors, Destructors,Function and


Operator Overloading
• Introduction :-
• C++ provides a special member function called as Constructor.
• A Constructor is an overloaded user defined function which enables an object to
initialize itself when it is created. This is known as automatic initialization of
objects.
• The main task of constructor is to initialize the objects of its class.
• The complement of the constructor is the destructor.
• A complementary user defined member function is applied automatically to each
class objects after the last use of that object is known as Destructor.
• Destructors are used to destroy an object.
• Constructor is automatically called when object is created.
• Constructors are also called when an object is created as part of another object.
• Functions :-
• Functions are the basic building blocks of C++ and the place where all
program activity occurs. A function is a group of statements that together
perform a task.
• A function is a subprogram that acts on the program data and often returns
values.
• A program written with numerous functions is easier to maintain, update
and debug than one very long or large program.
• Functions are used to implement large programs. In structured
programming functions are used to break the larger programs into smaller
ones; which makes debugging of program easier.
• Each function has its own name. When that name is encountered in a
program, the execution of the program branches to the body of that
function.
• Features of Functions:-
• The structure of a function definition is look like the structure of
main(), with it’s own list of variables declaration and program
statements.
• A function can have a list of zero or more parameters inside its
brackets, each of which has a separate type.
• A function may have more than one “return” statement in which
case the function definition will end execution as soon as the first
“return” is reached.
• Function declarations are like variable declaration, (function specify
which return type the function will return).
• A function has to be declared in a function declaration at the top of
the program and before it can be called by main().
• Advantages of Functions :-
• To reduce the size of a program by calling them at different places in
the program.
• Functions can be compiled separately
• Using functions, programs are easier to design, debug and maintain.
• Reuse of the function is possible in multiple programs.
• The functions provide interfaces to communicate with object.
• The function has following elements :
1. A Function Declaration
2. A Function Definition
3. A Function Call
4. Returning from function
1. A Function Declaration :-
• A function declaration tells the compiler about a function’s name, return
type and parameters.
• This is also referred as function prototyping.
• A function is declared with a prototype , which consists of return type, a
function name and argument list.
• Syntax :
• return_type function_name(argument1,argument2,…………..);
• A function can be declared either in the main function or in a class.
• For example,
• int add(int a, int b); //function add with 2 arguments
• void func(void); //function prototype with no arguments
• float display(); //function prototype with no arguments
2. Function Definition :
• The function definition tells the compiler what task the function will be
performed.
• Function definition consists of function prototype and actual body of a
function. It can be written anywhere in C++ program.
• The function definition consists of two parts :
i. Function Header or Prototype.
ii. Function body.
• The function header is similar to declaration.
• The function header is a replica of function declaration.
• The basic difference between these two is that the declaration in the
calling function will end with semicolon whereas; in the called function it is
not.
• The function body consists of local variables (if needed) and simple or
compound statements.
• Syntax :-
For Example :
• return _type function_name(argument list) int add(int a,int b) //function header
{
{ int total; //local variable
total = a+b;
local_variables declaration; return total; //function body
statements; }

}
• Here, argument list consists of any number of arguments with any
data type or no arguments.
• The return_type is the type of return value from the function.
• If we are using return statement, then return_type should be
specified otherwise void is used as return_type .
3. A Function Call:-
• Function can be called directly by simply writing the function name with
arguments or indirectly in the expression if it returns a value.
• We have to pass the actual parameters (arguments)to the functions. In the
function definition, the arguments are referenced. Therefore, calling a
function is also known as function reference.
• The arguments which we pass should match with the formal parameters
which are declared into the function. The data type and the order should
also be matched.
• For Example :
• add(x, y); //Function add called
• display(); //Function display called
• larger= max(a,b); //Function max called
• total = add(10,20) //Function add called
4. Returning from Function :-
• To return from function we use return statement.
• return statement pushes a value onto the return stack and control is
return back to the calling function.
• If return type is void , the function does not return any value.
• Syntax :-
• return; OR
• return value;
• Program : Program for function.
Output :
#include<iostream.h>
The first product is = 20
//using namespace std; The second product is =12
int mult(int a, int b) The third product is =20
{
int mul;
mul = a*b;
return(mul);
}
int main()
{
int x=3, y=4, z;
Z = mult(5,4);
Cout<<“The first product is =”<<z<<“\n”;
Cout<<“The second product is=”<<mult(x,y)<<“\n”;
Cout<<“The third product is=”<<mult(5,4);
return 0;
}
Static Members :
• C++ also allows us to use static members.
• The members declared inside the class but persisting from their
declaration to the end of program are called static members.
• The static members are both data members as well as member
functions.
• Static variables defined within a function only have a functions scope
so that they may not be accessed by any other function.
• Static Data Members:-
• In C++, a data member of a class can be qualified as static.
• Static variables are normally used to maintain values common to the
entire class.
• A static data member is useful when all objects of the same class
must share a common item of information.
• Static data members of a class are used to share information among
the objects of a class.
• Syntax for declaring a static data member :
static datatype datamembername;
OR
datatype static datamembername;
• When you proceed a member variables declaration with static, you
are telling the compiler that one copy of the variable will exist and
that of all objects of the class will share that variable.
• Characteristics of Static Data Member :-
1. All static variables are automatically initialized to zero value, when
the first object of the class is created.
2. Only one copy of static data member is created for the entire class
and is shared by all the objects of that class.
3. They are also known as class variables.
4. It is visible only within the class, but its lifetime is the entire
program.
5. Static data members are normally used to maintain values common
for all the objects.
6. The type and scope of each static variable must be redefined
outside the class definition.
7. Because static data members are stored separately rather than as a
part of an object.
• Program to read name ,post and salary of N employees. Post can be
manager or supervisor or worker. Add salary of all managers, supervisors,
workers and display it
/*Program to illustrate use of static data members in a class*/
#include<iostream.h>
#include<conio.h>
#include<string.h>
Class EMP
{
char name[10], post[10];
int salary;
public :
static int m_sum, s_sum, w_sum; //Variables for 3 posts
void get_data()
{
cout<<“\n Enter name, post & salary of an employee = ”;
cin>>name; if(x==0)
cin>>post; s_sum = s_sum +salary;
cin>>salary; x = srtcmp(post , “worker”);
} if(x==0)
w_sum = w_sum +salary;
void add_salary() }
{ void display_data()
int x; {
x = strcmp(post, “manager”); cout<<“\n”<<name
<<post<<salary;
if(x==0)
}
m_sum = m_sum +salary; }; //end of a class
x = srtcmp(post , “supervisor”);
//define static variables
int EMP::m_sum;
int EMP::s_sum;
int EMP::w_sum;
void main()
{
EMP E[10];
int N, i, temp;
clrscr();
cout<<“\n Enter total no. of employees = ” ;
cin>>N;
for(i=0;i<N;i++)
{
E[i].get_data();
E[i].add_salary();
}
cout<<“\n Name Post Salary”;
for(i=0;i<N;i++)
{
E[i].display_data();
}
cout<<“\n Total salary of all managers =”<<EMP::m_sum;
cout<<“\n Total salary of all supervisors =”<<EMP::s_sum;
cout<<“\n Total salary of all workers =”<<EMP::w_sum;
temp = EMP::m_sum + EMP::s_sum + EMP::w_sum;
cout<<“\n Total salary of all the employee in the company =”;
Cout<<temp;
getch();
} //end of main
• Output :-
Enter total no. of employees = 4
Enter name, post & salary of an employee = Prajakta manager 10000
Enter name, post & salary of an employee = Pranjal supervisor 8000
Enter name, post & salary of an employee = Vaishali worker 5000
Enter name, post & salary of an employee = Megha worker 4000
Name Post Salary
Prajakta manager 10000
Pranjal supervisor 8000
Vaishali worker 5000
Megha worker 4000
Total salary of all managers = 10000
Total salary of all managers = 8000
Total salary of all managers = 9000
• A static variable can be accessed either using object or using the class
name. The scope resolution operator must be used when class name is
used to access static data.
• By using static member variables, the need for global variables can be
eliminated. Since, static variables are associated with the class itself rather
than class object ;they are also called as class variables.
• In above program, observe that the static variables are declared within the
class but defined outside the class. This is necessary to emphasize that the
memory space for static data is allocated only once before the program
starts execution and is shared by entire class. So this is similar to global
data.
• The following diagram makes the concept more clear.
E[0] E[1] E[2] E[9]

Name: Name: Name: ………………………. Name:


Dipak Pankaj Nilesh Roshan

m_sum Static data


s_sum Common for all
w_sum Objects
• Even if the static data members are private, then also it is necessary
to define them outside the class. Also note that, the static data
members are initialized to zero by default. We can initialize them to
any value at the time definition.
• For example : int EMP:: m_sum =100;
• This statement will initialize m_sum to 100 instead of zero.
• One more use of static data members is to keep count of total
number of objects created for that class.
Static Member Functions :
• Member functions may also be declared as static.
• A static function can have access to only other static members declared in the
same class.
• But there are some restrictions on them :
1. They may only access other static members of the same class directly.
2. They do not have a ‘this’ pointer.
3. There cannot be a static and non-static version of the same function.
• It can be called using class name as,
class_name::function_name
Syntax of declaring a static member function :
static return_type function_name(arguments);
OR
return_type static function_name(arguments);
Syntax for calling static member function :
class_name::member-function-name;
• Display a class which displays the number of times display operation is performed.
#include<iostream.h> int main()
class display {
display ob1,ob2,ob3,ob4;
{ ob1.disp();
private : ob2.disp();
ob3.disp();
static int count; ob4.disp();
public : //function call with class name
display::disp();
static void disp() }
{ Output:
1
count++; 2
cout<<count<<endl; 3
4
}
5
}; Press any key to continue…
int display::count; //defining static variable outside a class
• The statement count++ is executed when disp() function is invoked and the current value of count
is assigned to each object.
Interaction Between Function :
• The function [main() and other] interacts with each other through
parameters. We pass the parameter to the function for the
communication of calling function and called function.
• There are two types of parameters :
1. Actual parameters (used in the function call)
2. Formal parameters (used in function definition)
Call by Reference :
• When a function is called the address of the actual parameters are
copied on to the formal parameters, though they may be referred by
different variable names.
• This content of the variables that are altered within the function block
are return to the calling function program. As the formal and the
actual arguments are referencing the same memory location or
address.
• This is known as call by reference, when we use this concept with
functions.
oCalled function makes the alias of the actual variable which is passed.
oActual variables reflect the changes made on the alias of actual
variables.
oNumber of values can be modified together.
• For call by reference concept C++ uses a reference operator (&).
• ‘&’ operator allows true call by reference functions, eliminating the need to
dereference arguments passed to the function.
• The ‘&’ operator is placed before the variable name of argument in the
parameter list of function. Then the function can be called without passing
the address and without dereferencing within the function.
• Program to swap the values by call by reference.
Output:
#include<iostream.h> int main()
25 30
void swap(int &p, int &q) {
After Swap
int x=25, y=30;
{ cout<<x<<“\t”<<y<<endl;
30 25
int dummy; swap(x,y);
dummy = p; cout<<“After swap
”<<endl;
p=q; cout<<x<<“\t”<<y;
q=dummy; }
}
• Let us see how this program gets executed in the memory. As shown
in Figure.
• In fig. p is alias of x and q is alias of y. Therefore, we do not need
4bytes allocated for p and q,[each will have 2 bytes].
• Here, it first copies the value of x i.e. p to dummy. Then the value of q
or y is assigned to p and then the value of dummy is assigned to y or
q. In this way the values are swapped without wasting more amount
of memory. This is because the formal parameters are of reference
type.
• The compiler always treats them similar to pointer but compiler does
not allow the modification of the pointer value. The changes made to
the formal parameters p and q are reflected on the actual parameters
x and y as shown in figure.
• Fig. : Call by Reference x
25 p

1 dummy
2

y
3
30 q

• The following points can be noted about reference parameters :


1. Here, parameters passed to a function by its reference and not by it’s value.
Reference means address of variable is passed to function.
2. A reference cannot null.
3. It should always refer to an object or a vriable.
4. Once, a reference points towards one object or variable, then it cannot be
changed. Even it should not point towards different object.
5. The reference does not require any explicit mechanism to
dereference the memory. Whenever the program execution
terminates, all the memory locations gets free. References are also lost.
6. It is good for performance because it eliminates the overhead of
copy large amount of data.
• Return by Reference :-
• The function can also return the reference of variable. This reference
variable is actually an alias for the referred variable.
• The method of returning reference is used generally in operator
overloading. This method will form a cascade of member function
calls.
• For example : cout<<k<<a;
This statement is a set of cascaded calls which returns reference to
the object cout.
• Program for function which returns value by reference.
#include<iostream.h>
int &Large(int &m, int &n); //function prototype
int main()
{
int a,b,m,n;
cout<<“Enter values for two integers”;
cin>>a>>b;
//fuction call is given
//reference which is returned is assigned to -1
Large(m,n)= -1;
cout<<“First number”<<m;
cout<<“second number”<<n;
}
int &Large(int &p, int &q)
{
if(p>q)
return p; //function returns the value through reference
else
return q;
}
Output :
Enter values for two integers 10 20
First number 10
Second number -1
If we execute the program one more time then output will be :
Enter values for two integers 8 3
First number -1
Second number 3
• When program gets executed, it returns the reference to the variable which holds the
larger value. And this assigns the value -1 to it.
Inline Function :-
• C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.
• Any changed to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
• The advantage of using function is to save the memory space. Consider a
situation where a small function is called number of times calling a
function requires certain overheads such as:
• Passing to the function.
• Passing the values or push arguments into the stack.
• Save the registers.
• Return back to calling function.
• In C++, compiler put the code directly inside the function body of
calling program. Every time when function is called, at each place the
actual code from the function would be inserted, instead of a jump to
the function. Such functions are called inline functions.
• A function can be defined as an inline functions by writing the
keyword inline to the function header as shown below:
inline function_name(list of arguments)
{
//function body
}
• When we do not specify keyword inline then only one copy of
function code(object code) is called depending upon the functions
calls.
• As shown Fig. :
• Fig. : Calls given to a Function :
Object code for nth Call
function

First Call Second Call Third Call

• But as we said above, lot of time is needed for all these calls to execute. If
we make this function inline then the calling statement is replaced with
the function code. So it minimizes the time spent on jumping , pushing
arguments and so on. This shown in Fig. Calls given to Inline Function
Object code for Object code Object code
function -------------- for function
for function

Second
First call ------------- nth call
call
• Program illustrates the use of inline function to compute square of number.
#include<iostream.h>
inline int sq(int x)
{
int p;
p = x*x; Output:
return p; Enter number 12
} Square is 144
int main()
{
int n;
cout<<“Enter number” ;
cin>>n;
cout<<“Square is”<<sq(n)<<endl;
}
Friend Function :
• The functions that are declared with the keyword friend are known as
Friend Function.
• To make an outside function friendly to a class, we have to simply
declare this function as a friend of the class.
• A friend function is a function that is not a member of a class but has
access to the class’s private and protected members.
• Friend functions are not considered class members ; they are normal
external functions that are given special access privileges.
• Friends are not in the class’s scope, and they are not called using the
member selection operators (. and ->) unless they are members of
another class.
• For example:
class xyz
{
……
public :
……..
……..
friend void abc(void);
};
• The function declaration in above example should be preceded by the
keyword friend.
• Program for friend function.
float mean(friendtestdemo f)
#include<iostream.h>
using namespace std; {
class friendtestdemo return float(f.x + f.y)/2.0;
{ }
int x,y; int main()
public : {
void setvalue() friendtestdemo A;
{ A.setvalue();
x=20; cout<<“Mean value
y=50; =”<<mean(A)<<“\n”;
} return 0;
friend float mean(friendtestdemo f) ; }
}; Output :
Mean value = 35;
Function Overloading :
• C++ provides the facility of function overloading in which we can
define multiple functions with the same name but the types of
arguments are different.
• For example, we can have a function add with two floating point
numbers as arguments, another function adds with 3 integers, one
add function with 4 doubles and so on. But function name is similar.
This is called as Function Overloading.
• An overloaded function is a function with the same name as another
function, but with different parameter types.
• The function overloading can be performed using single and many
objects. This is shown in following fig.:
Function Overloading

Many Objects Single Objects

• Same function name with • Same function name with


different argument list. different argument list.
• Different objects are created. • One object is created.
• A call is given to different arg-list • A call is given to different arg-list
functions with each object. function with one object.

• Rules for overloaded functions :-


1. The argument list of each of the function instances must be different.
2. The complier does not use the return type of the function to distinguish
between function instances.
• Program for function overloading with many objects.
#include<iostream.h>
class test int main()
{ {
public : test ob1, ob2, ob3;
void addnum(int p, int q, int r) ob1.addnum(5, 8, 10);
{
ob2.addnum(2.5, 3.6);
cout<<“Sum is”<<p+q+r<<“\n”;
ob3.addnum(25, 3.5);
}
}
void addnum(float p, float q)
{
Output :
cout<<“Sum is”<<p + q<<“\n”; Sum is 23
} Sum is 5.6
void addnum(int p, double q) Sum is 28.5
{
cout<<“Sum is”<<p + q<<“\n”;
}
};
• Program for function overloading with single object.
#include<iostream.h>
Class test
{ int main()
void addnum(int p, int q, int r) {
{ test ob1;
cout<<“Sum is”<<p+q+r<<“\n”; ob1.addnum(5, 8, 10);
} ob1.addnum(2.5, 3.6);
void addnum(float p, float q) ob1.addnum(25, 3.5);
{ }
cout<<“Sum is”<<p + q<<“\n”;
Output :
}
Sum is 23
void addnum(int p, double q)
Sum is 5.6
{
Sum is 28.5
cout<<“Sum is”<<p + q<<“\n”;
}
};
Constructors :
• A constructor is a special member function which is used to allocate memory
space and value to the data members of that objects.
• A constructor makes the object functional by converting an object with the
unused (uninitialized) memory into a usable (initialized) object.
• Whenever, an object is created, the constructor will be executed automatically
and initialization of data member takes place.
• It is called constructor because it constructs the value of data member of the
class.
• A constructor is a special as it has the same name as that of the class and is
automatically invoked whenever an object of the class is created.
• When we declare an object in function main() :
1. Memory will be allocated.
2. Constructors will be called by the compiler automatically.
3. Initialization of variables (data member) takes place.
• It is not possible for us to initialize the data member in the class declaration itself.
Because at that point memory is not allocated for the object.
• Syntax Rules for writing Constructor Functions :
• The following are the rules used for writing a constructor. These are
also referred as characteristics of constructors.
1. A constructor’s name must be same as the class name in which it is
declared.
2. It does not have any return value.
3. It is generally declared as a public member function. It may have
protected access within the class and only in rare circumstances it
should be declared private.
4. It can have default argument.
5. It can not be declared constant, variable, static or virtual.
6. It can not be referred by its address.
7. It can not be inherited like other functions.
8. The implicit calls are given to the operators new and delete when memory allocation is
required.
9. It is automatically called when an object is created.
10. It specifies how an object is created.
• Like other member functions of the class, a constructor can also defined either inside or
outside the class definition.
• Syntax to define a constructor (Inside the class)
• Class class_name
{
:
public :
class_name(parameter_list) //header of the constructor
{
//body of the constructor
}
};
Where, parameter_list is optional.
• Example :
//class with constructor
Class time
{
int hour;
int min;
public :
time()
{
hour = min = sec = 0; //initialization
}
}
• A constructor can also be declared outside the class using the scope
resolution operator (::).
• Syntax to define the constructor (Outside the class):-
class class_name
{
:
public :
class_name(parameter_list) ; //constructor prototype
:
};
class_name::class_name(parameter_list) //constructor definition
{
//body of the constructor……………….
}
Where, parameter_list is optional.
• Example:
//Class with constructor • When a class is declared with the
class time constructor as above, then object is
{ created by the class will be initialized
int hour; automatically. For example: time t;
• Here, object t is created and it
int min; initializes data members: hour, min,
public: sec to zero. There is no need to write
time(); //constructor declared any statement to invoke the
} constructor function (as we do with
normal function) .
time::time
{
hour = min = sec = 0; //initialization
}
• Program for Constructor. void Line::setLength(double len)
#include<iostream.h> {
length = len;
using namespace std;
}
class Line double Line::getLength()
{ {
public : return length;
void setLength(double len); }
int main()
void getLength(); {
Line(); //This is the constructor Line line;
private : line.setLength(6.0);
double length; cout<<“Length of line
:”<<line.getlength()<<endl;
};
return 0;
Line::Line() }
{ Output :
cout<<“Object is being created”<<endl; Object is being created
} Length of line : 6
Constructor Call :-
• For calling of a defined constructor there are two ways namely, explicit call and
implicit call.
• If the name of the constructor is not used in the object declaration, the call is
known as an implicit call to the constructor. While, if the name of the constructor
is used in the object declaration, the call is known as an explicit call to the
constructor.
1. Explicit call : In this method name of constructor with the values of variables in
the bracket are coming in the picture, to construct the values. Name of
constructor is explicitly mentioned in the program, so this method is known as
explicit call of constructor.
For example : Bank b1;
b1 = Bank(12) ;
2. Implicit Call : It will not show name of constructor in the program. Values of the
variables get constructed at the time of objects declaration.
For example :Bank b1(50) ;
• Program for calling of constructor implicitly and explicitly.
#include<iostream.h>
int main()
using namespace std; {
Class display display disp; //implicit call
{ display displ = display(); //explicit call
return 0;
int a,b; }
public : Output :
display() //constructor Value of a and b is : 1,2
Value of a and b is : 1,2
{
a=1;
b=2;
cout<<“Value of a and b is :”<<a<<“,”<<b<<endl;
}
};
Types of Constructor :
Types of Constructor

Parameterized Dynamic Constructor


Default Constructor Copy Constructor
Constructor

1. Default Constructor :-
• The constructor which does not accept any arguments is called default constructor.
In default constructor the argument list is void.
• Default constructor is also called as empty constructor because of it has no
arguments. A default constructor is used to initialize all the objects of a class with
the same values.
• There can be only one default constructor in a class. The default constructor is
defined as, “a constructor which does not contain any parameters/arguments”.
• A default constructor can be called directly when an object of the class is created. If no
constructor is created, compiler will create a default constructor by itself.
• Syntax:-
class class_name() For Example :-
{ student :: student()
:
{
public :
rollno = 0;
class_name()
marks = 0.0;
{
//body of constructor
}
}
:
:
};
The Diagrammatic representation of default constructor in Fig. :
No Parameters Passed
main() constructor
Creation of object Initialization of data
members
• Program for generation of Fibbonacci series using default constructor
and scope resolution operator.
#include<iostream.h>
using namespace std;
Class fibo
{
private :
int fib0, fib1, fib2;
public :
fibo(); //default constructor declaration
void disp();
void increment();
};
// Outside class scope resolution operator is used
fibo::fibo()
{ void fibo :: disp()
{
fib0 = 0; cout<<fib2<<“\t”;
fib1 = 1; }
int main()
fib2 = fib0 +fib1; {
} fibo ob1;
for(int i=0;i<=15;i++)
void fibo::increment() {
{ ob1.disp();
fib0 = 0; ob1.increment();
}
fib1 = 1; return 0;
fib2 = fib0 +fib1; }
Output :
} 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
2. Parameterized Constructor :-
• Sometimes, it is essential to initialize the various data elements of
different objects with different values when they are created.This is
achieved by passing arguments to the constructor function when the
objects are created.
• The constructors which accept any number of formal parameters and
that formal parameters are used to initialize the object are called
parameterized constructor.
• A parameterized constructor is defined as, “a constructor which
accepts one or more arguments/parameters at the time of
declaration of objects and initializes the data member of the objects
with these parameters/arguments” .
• Syntax to define a parameterized constructor : For Example:
class class_name(); student:: student(int r)
{ {
: rollno = r;
public: }
class_name()(param1,param2,…..paramN) • These parameters are passed at
{ the time of object
//body of the constructor…… creation.These parameters can
} be of any data type except it’s
: own class data type.
}; • The diagrammatic
representation is shown in Fig. :
Initial value passed
Constructor
main()
Initialization of data
Creation of object
members
• Program for Parameterized Constructor.
#include<iostream.h> int main()
using namespace std; {
Class sample sample ob1(15); //value passed
{ through object
private : ob1.disp();
int k; return 0;
public : }
sample(int p) //parameterized Constructor Output :
{ 15
k=p;
}
void disp()
{
cout<<k;
}
};
• The output of above program is 15.The formal parameter value is
passed to the constructor where actual parameters gets this formal
value and initialization of object is done.
• The passing of argument can be done in following way:
1. Call a constructor explicitly.
2. Call a constructor implicitly.
• Previous Program, is the example of implicit call. Here the values are
passed through the objects. Sometimes, the constructor itself
consists of certain default values. If the values are passed to the
constructor, it will consider the default values. This is referred as
explicit call.
• Program for parameterized constructor with implicit and explicit call.
#include<iostream.h>
void disp()
using namespace std; {
class sample cout<<k;
{ }
private: };
int k; int main()
public: {
sample ob1(10); //implicit
sample(int p)
sample ob2 = sample(20); //explicit
{ ob1.disp();
k=p; ob2.disp();
} return 0;
• Implicitly the default value of }
Output :
constructor is assigned to ob2. 10 20
3.Copy Constructor :-
• A copy constructor takes a reference to an object of the same class as
itself as an argument.
• A constructor that initializes an object using values of another object
passed to it as parameter is called copy constructor.
• In C++, a new object of a class can also be initialized with an existing
object of the same class. For this, the compiler of C++ calls the copy
constructor.
• Copy constructor creates the copy of the passed object.
• A copy constructor is defined as, “a constructor which accepts an
already existing object through reference to copy the data member
values”.
• Syntax to define a copy constructor :
class class_name
{
:
public :
class_name ( class_name & object_name)
{
// body of the constructor……….
}
};
• As with all constructors, the function name must be the class name. The
parameter in the declaration is a reference to the class, which is a
characteristic of all copy constructors.
• While defining the copy constructor, it is recommended to specify the
keyword const for the reference parameter. This is because the existing
object is used only to initialize the new object and cannot be changed by
the copy constructor.
• Syntax :
class class_name
{
:
public:
class_name(const class_name & object_name)
{
//body of the constructor
}
:
};
• To invoke a copy constructor use following syntax:
class_name new_object = existing_object; OR
class_name new_object (existing_object);
• The existing object is the object whose copy is to be created and
stored in new object.
• The argument is passed through reference and not through value.

main() Constructor
Reference of object of same class
Creation of Initialization of data
object members

• For example :
student ::student(student &t)
{
rollno = t.rollno;
}
• Program for copy constructor. Sample ::sample(sample &s)
#include<iostream.h> {
x = s.x; ///existing object and data
using namespace std; y = s.y;
class sample }
{ void sample:: disp()
{
private :
cout<<x<<“ ”<<y<<endl;
int x,y; }
public : int main()
sample(); //Default constructor {
sample ob1;
sample(sample &) //Copy Constructor definition sample ob2(ob1); //invoking copy constructor
void disp(); sample ob3 = ob1; //invoking copy constructor
}; ob1.disp();
ob2.disp();
sample::sample() ob3.disp();
{ }
x=10; Output :
10 20
y = 20; 10 20
} 10 20
4. Dynamic Constructor :-
• Allocation of memory to objects at the time of their construction is
known as Dynamic construction of objects.
• The memory is allocated with the help of the new operator. The
constructor can also be used to allocate memory while creating
objects.
• This will enable the system to allocate the right amount of memory
for each object when the objects are not of the same size, thus
resulting in saving of the memory.
• The word dynamic is related with the memory allocation.Programmer
can explicitly assign memory to variables and after completion of
operation we can delete that memory.
• ‘new’ is the keyword used for assigning memory locations to
variables while ‘delete’ is the keyword used for deleting memory
locations.
• By using these two keywords memory can be effectively
managed.
• The constructor can also be used to allocate memory while
creating objects. For this purpose new and delete keywords are
allowed in the body of constructor.
• A dynamic constructor is defined as, “a constructor in which the
memory for data member is allocated dynamically”.
• Dynamic constructors are used to allocate memory to objects at
run-time rather i.e., allocating memory to objects when they are
created.
• Program for Dynamic Constructor.
#include<iostream.h> int Display()
using namespace std; {
class Dynamic return (*ptr);
{ }
int *ptr; };
public : int main()
Dynamic : {
{ Dynamic d1;
ptr = new int; Dynamic d2(2000);
*ptr = 1000; cout<<d1.display();
} cout<<d2.Display();
Dynamic(int v) }
{ Output :
ptr = new int; 1000
*ptr = v; 2000
}
• Program to create memory space for a class object using the new
keyword and to destroy it using delete keyword.
#include<iostream.h> void sample :: getdata() Output:-
{ Enter an integer value: 7
using namespace std; cout<<“Enter an integer value \n”; Enter float value : 6.7
class sample cin>>x; x = 7 y = 6.7
cout<<“Enter float value \n”;
{ cin>>y;
}
private : void sample :: display()
{
int x; cout<<“x=”<<x<<“\t”<<“y=”<<y;
float y; }
int main()
public : {
sample *ptr; //pointer declaration
void getdata(); ptr = new sample; //dynamic memory allocation
void display(); ptr -> getdata();
ptr -> display();
}; delete ptr; //releasing allocated memory
}
• Destructor :-
• Destructor is a special member function which is called automatically
whenever a class object is destroyed.
• The primary usage of the destructor function is to release space on the
heap. Whenever, a particular object goes out of the scope of its existence,
destructors will be called automatically and it takes out the allocated
memory.
• Destructors are invoked by the compiler implicitly when the termination of
program takes place. But it is always better to invoke the destructor
explicitly by writing it into the program code.
• The diagrammatic representation of the destructor is shown in fig. :
No Parameter passed
main() Destructor
End of the Release the memory
program location with the use
No value is returned of delete
• A destructor is also special as it has same name as that of the class of which it is a
member but with a ̰ (tilde) sign prefixed to it’s name and which is used to destroy the
objects that have been created by a constructor. It gets invoked when an object’s scope is
over. • For Example:
• Syntax of Destructor :- class sample
class class_name {
{ private :
: //data variables
public : //member functions
class_name(); { } public :
class_name() //header of the destructor sample();
{ //constructor
//body of the destructor…… ̰sample(); //destructor
}
//member functions

};
};
• A destructor releases the resources and memory at run-time to clean up the unused
storage area.
• Syntax Rules for Writing Destructor Functions :
1. A destructor name must be same as the class name in which it
is declared, prefixed or preceded by a symbol tilde ( ̰).
2. It does not have any return value.
3. It is declared as a public member function.
4. It takes no arguments and therefore cannot be overloaded.
5. It cannot be declared static , constant, variable or volatile
i.e.virtual.
6. It is automatically called when the object is destroyed .
7. It specifies how an object is deleted.
• Program for destructor.
void main()
#include<iostream.h> {
using namespace std; sample ob1, ob2, ob3;
Class sample }
{ Output :
10 20
private : 10 20
int k,m; 10 20
public : • The objects deleted are :
ob3
sample()
ob2
{ ob1
k=10; • If more than one object is defined,
m=20; constructors are invoked from right
to left i.e., from first object to last .
cout<<k<<“\t”<<m<<endl;
• But destructors are invoked in
} reverse order like a stack.
̰sample() { } //destructor • so first created object will get
}; deleted list.
• Program to declare a class having data members as hrs. mins. and secs. Write
constructor the values and destructor to destroy values. Accept and display data
for two objects.
void display()
#include<iostream.h> {
using namespace std; cout<<“Time = ”<<endl;
class time cout<<hr<<“: ”<<min<<“:”<<sec;
{ }
̰time()
int hr; {
int min; cout<<“Destructor invoked”;
int sec; }
public : };
int main()
time (int h, int m, int s) {
{ time t1(3, 30, 50);
hr=h; time t2(4, 15, 35) ;
t1.display();
min = m;
t2.display();
sec = s; return 0;
} }
• Output :-
Time = 3 : 30 : 50
Time = 4 : 15 : 35
Destructor invoked
Destructor invoked
• In above program t2 object will destroyed first and then t1 object
will destroyed because destructors are called in opposite
direction of constructors.
• Difference between Constructor and Destructor
Terms Constructor Destructor
Purpose It allocates the memory to an object. It deallocates the memory to an object.

Declaration class _name(arguments if any) ~class _name( )


Syntax { {
//Body of Constructor //Body of Destructor…
}; };

Arguments Constructor accepts arguments. Destructor does not accept any argument.
Calling Constructor is called automatically, Destructors are invoked /called by the compiler
when a new object of a class is implicitly when the termination of program takes
created . place.
Name Constructor has the same name as Destructor also has the same name as class name
class name. but with a tilde(~) prefixed to its name.
Use Constructor is used for initializing the Destructor is used when the object is destroyed
values to the data members of the or goes out ofscope.
class.
In numbers There can be multiple constructors in There is always a single destructor in the class.
the class
Terms Constructor Destructor
Overloading Constructors can be overloaded. Destructor cannot be overloaded.
Return type Constructors never have a return type even void. A destructor neither accepts any parameter nor has
a return type (not even void).
Types In C++, Program we can use different types of In C++, Program a single destructor is used to
constructors like default constructor, destroy all the objects of a class created either
parameterized constructor, copy constructor etc. using default , parameterized or copy constructor.
Example class student class test
{ {
private: private :
int marks; int a;
char grade; public:
public: test()
student(int m, char g) {
{ cout<<“Object is created :”<<endl<<endl;
marks m; }
grade g; ~test()
} {
void show() cout<<“Object is destroyed ”<<endl<<endl;
{ }
cout<<“Marks =”<<marks<<andl; };
cout<<“Grade = ” <<grade<<endl;
}
Operator Overloading :
• Operator overloading is closely related to function overloading.
• Operators can be overloaded by creating ‘operator functions’.
• An operator function defines the operations that the overloaded operator will perform
relative to the class upon which it will work.
• An operator function is created using the keyword ‘operator’.
• A operator function’s general form is :
return_type class_name :: operator op(arg-list)
{
//operations
}
• Where, return-type is the type of value returned by the specified operation and
op is the operator being overloaded.
• For example, if you are overloading the / operator , use ‘operator /’.
• When an unary operator is overloaded , arg-list is empty.
• When a binary operator is overloaded, argument-list will contain one parameter.
• Operators that can be overloaded except the following :-
. Member access operator
.* Pointer to member operator
:: Scope resolution operator
?: Conditional Operator
sizeof sizeof operator
• All operators are divided into three categories :
C++ Operators

Unary Binary Ternary


• Unary :
• It requires only one operand to perform operation.
• For example : i++;
• Here, i is the single operand to perform increment operation.
2. Binary :
• It requires two operands to perform operation.
• For example : a + b;
• Here, a and b are two operands to perform addition operation.
3. Ternary Operator :
• It requires three operands to perform operation.
• Ternary operator is ?:
• For example : x>5 ? y=2 : y=1;
• This line compares x value . If x>5 , y=2. If x is not greater than y=1.
• Overloading means assigning more than one meaning to operator .
• For example, + sign can be used for :
1. Addition of two integers.
2. Addition of two complex numbers
3. Addition of two characters.
• Steps for operator overloading are given below :
1. Create a member function under a public section.
2. The member function is called as operator overloaded function so,
syntax of declaration than other normal member function.
3. Syntax :-
return_type operator op()
{
//details of operation
}
• Here, operator is a keyword which tells it is operator overloading
function and op is any operator.
• For example, +
3. When we want to call operator overloading function the syntax is:
operator sign object_name;
For example : For calling +sign’s operator overloaded function we will
use, +a1;
Here, a1 is the object of class where operator overloading function is
declared.
Rules for Overloading Operators :
• Although it looks simple to redefine the operators, there are certain
restrictions and/or limitations in overloading them. Some of them are
listed below :
1. Only existing operators can be overloaded. New operators cannot be
created.
2. The overloaded operator must have at least one operand that is of user
defined type.
3. We cannot change the basic meaning of an operator. That is we cannot
redefine the plus(+)operator to subtract one value from the other.
4. Overloaded operators follow the syntax rules of the original operators
that cannot be overridden
5. There are some operators that cannot be overloaded such as .*,:: etc.
6. Unary operators, overloaded by means of a member function, take
no explicit values. But those overloaded by means of a friend function
take one reference argument.
7. Binary operators overloaded through a member function take one
explicit argument and those which are overloaded through a friend
function take two explicit arguments.
8. When using binary operators overloaded through a member function,
the left-hand operand must be an object of the relevant class.
9. Binary arithmetic operators such as +,-,*,/ must explicitly return a
value . They must not attempt to change their own arguments.
10. We cannot use friend functions to overload certain operators, which
are listed below. However, member functions can be used to overload
them.
= Assignment Operator
() Function call operator
[] Subscripting operator
-> Class member access operator.
Where, a friend cannot be used.
Overloading Unary and Binary Operators:
1. Overloading Unary Operator :
• The Operators can be overloaded using two different
functions i.e. through member functions and friend
functions.
• A unary operator overloaded using a member function takes
no argument, whereas an overloaded unary operator
declared as friend function takes one argument.
• The unary operator that can be overloaded are shown below.
• Table : Unary Operator

Operators Meaning
-> Indirect member operator
! Logical negation
* Pointer reference
:& Address Operator
~ Ones Complement
->* Indirect pointer to member
+ Addition
- Subtraction
++ Incrementer
-- Decrementer
- Unary minus
• First, we will consider the unary minus (-) operator . A minus
operator, when used as a unary, takes just one operand.
• We know that this operator changes the sign of an operand
when applied to a basic data item. We will see here how to
overload this operator so that it can be applied to an object
in much the same way as is applied to an int or float variable.
• The unary minus when applied to an object should change
the sign of each of its data items.
• Program for how the unary minus operator is overloaded.
#include<iostream.h>
class space void space::display()
{ {
int x; cout<<x<<“ ”;
int y; cout<<y<<“ “;
int z; cout<<z<<“\n”;
public : }
void getdata (int a, int b, int c) ; void space:: operator –() //defining operator –()
void display();
{
void operator –(); //overload unary minus
x = -x;
};
y = -y;
z = -z;
void space::getdata()
}
{
x=a;
y=b;
z=c;
}
int main()
{
space s;
s.getdata(10,-20,30) ;
cout<<“s : before overloading :”;
s.display();
-s; //activities operator –()
cout<<“s : After overloading :”;
s.display();
}
Output :-
s : before overloading : 10 -20 30
s : After overloading : -10 20 -30
• Note that, function operator –() takes no argument. Then what does this operator
function do? It changes the sign of data members of the objects.
• Since, this function is a member function of the same class; it can directly access
the member of the object which activated it.
• Remember a statement like : s2 = -s1;
will not work because, the function operator –() does not return any
value.
• It can work if the function is modified to return an object.
• It is possible to overload a unary minus operator using a friend function as
follows:
friend void operator –(space &s) //declaration
void operator –(space &s) //definition
{
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
}
• Note that, the argument is passed by reference. It will not work if we
pass argument by value because only a copy of the object that
activated the call is passed to operator –().
• Therefore, the changes made inside the operator function will not
reflect in the called object.
Overloading of increment Operator :
• We know that C++ supports the operator that is used for
incrementing and decrementing by 1. These operators can be used
either prefix or postfix.
• Generally, overloading of these operators cannot be distinguished
between prefix or postfix operation. But whenever a postfix operation
is overloaded, it takes a single argument along with a member
function of a class.
• Program to generate Fibonacci series by :-
#include<iostream.h>
class fibo
{
private :
int fib0, fib1, fib2;
public :
fibo(); //default constructor
void operator ++() //Overloading declaration
void disp();
};
fibo::fibo()
{
fib0 = 0;
fib1 = 1;
fib2 = fib0 +fib1;
}
void fibo::disp() int main()
{ {
fibo ob1;
cout<<fib2<<“\t”; int n;
} cout<<“How many numbers you want ?:”;
cin>>n;
void fibo :: operator ++() for(int i=0; i<=n; ++i )
{ {
fib0 = fib1; ob1.disp();
++ob;
fib1 = fib2; }
fib2 = fib0 + fib1; }
Output:-
} 4
1 2 3 5 8
2. Overloading Binary Operator :
• Binary operators are operator which requires two operands to operation.
• We have just seen how to overload a unary operator. The same mechanism can be used to overload a binary
operator.
• To add two numbers generally we use statement like :
c = sum(A,B); //Functional notation
• The functional notation can be replaced by a natural looking expression, C = A + B //arithmetic notation
• By overloading the + Operator using an operator +() function.
• The binary operators overloaded through member function take one argument which is formal.
• The Table shows the binary operators which can be overloaded. The binary overloaded operator function
takes the first object as an implicit operand and the second operand must be passed explicitly.
• Syntax for overloading a binary operator is :
keyword Operator to be overloaded

return_type operator operator_symbol (arg)


{ argument to operator function
// Body of oerator function
}
• Table : Binary Operators
Operator Meaning
[] Array element reference
() Function Call
new New Operator
delete Delete Operator
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
<< Left shift
>> Right shift
< Less than
<= Less than or equal to
> Grater than
>= Grater than or equal to
Operator Meaning
== Equal
!= Not equal
& Bitwise AND
^ Bitwise XOR
&& Logical AND
| Logical OR
= Assignment
*= Multiply and Assign
/= Divide and Assign
%= Modulus and Assign
+= Add and Assign
-= Subtract and Assign
<<= Shift left and assign
>>= Shiftright and assign
&= Bitwise AND and assign
:= Bitwise OR and assign
^= Bitwise one’s complement and assign
• Program for Binary Operator overloading :
#include<iostream.h>
using namespace std;
class integer
{
private :
int val;
public :
integer(); //constructor1
integer(int one) ; //constructor2
integer operator +(integer objb); //operator function
void disp();
};
integer :: integer() void integer ::disp()
{ {
cout<<“value=”<<val<<endl;
val = 0; }
} int main()
integer::integer(int one) {
integer obj1(11);
{ integer obj2(22);
val = one; integer objsum;
} objsum = obj1 + obj2; //operator
overloading
integer integer ::operator +(integer objb) obj1.disp();
{ obj2.disp();
integer objsum; objsum.disp();
}
objsum.val = val + objb.val; Output :
return(objsum); value = 11
} value = 22
value = 33
• Operator Overloading Using friend Function :
• We have already seen that private members of a class cannot be
accepted through outside functions. This is possible just by using
friend function concept.
• Friend functions may be used in place of member functions for
overloading a binary operator.
• The difference is friend function requires two arguments to be
explicitly passed to it while a member function requires only one.
• Overloading Binary Operators using ‘friend’ Functions :-
• The Syntax for declaring and defining a friend operator function to
overload binary operator is as follows:
class class_name
{
public:
friend return_type operator op(arg1, arg2);
};
return_type operator op(arg1, arg2,----argN)
{
// function definition
}
• Program for overloading binary operator using friend function.
#include<iostream.h>
class binopr
{
private:
int x;
public:
binopr() { } //constructor
binopr(int); //parameterized constructor
void disp();
friend binopr operator +(binopr, binopr);

};
binopr:: binopr(int a)
{ int main()
{
x=a; binopr ob1, ob2, ob3;
} ob1 = binopr(15);
void binopr::disp() ob2 = binopr(28);
ob3 = ob1 + ob2;
{
ob3.disp();
cout<<x; }
} Output :
//overloading definition with friend function 43
binopr operator +(binopr P, binopr S)
{
return (P.x + S.x);
}
• The overloading definition can also be written using following code:
• binopr operator +(binopr P, binopr S)
{
S.x = P.x + S.x;
return(S.x) ;
}
• The implementation of overloading +operator(binary) is shown in Fig.
Overloading Unary Operators using ‘friend’ Function :-
• Here, the operator function is not the member function of any class.
• Hence, in this scenario if an operator has to be overloaded to make it work on a
class object, the operator function has to be declared as a friend to that class.
• It is to be noted that, when an operator function is friend to a class, then we can
call that function as a “friend operator function”.
• The syntax for declaring and defining a friend operator function to overload an
unary operator is as follows :
class class_name
{
public :
friend return_type operator op(arg);
};
return_type operator op(arg)
{
//function definition……..
}
• Program for overloading unary operators using friend function.
#include<iostream.h>
using namespace std;
class OverUnaOpr
{
private :
int x;
int y;
public:
friend void operator –(overUnaOpr &); //prototype
void display();
OverUnaopr() //constructor
{
x=6;
y = 7;
}
};
void operator –(OverUnaOpr &a) //Operator function definition
{ int main()
a.x = -a.x; {
OverUnaOpr s;
a.y = -a.y; s.display();
} -s; //Overloading unary ‘-’ operator
s.display();
void OverUnaOpr::display()
return 0;
{ }
cout<<“x=”<<x<<endl;
Output :
cout<<“y=”<<y<<endl; x= 6
} y =7
x = -6
y = -7
Overloading Insertion (<<) And Extraction (>>) Operators :-
• We have already used the objects cin and cout (predefined in
iostream file) for the input and output of data of various types. This is
possible only because the operators >> and << are overloaded to
recognize all the basic C++ types.
• The >> operator is overloaded in the istream class and << operator is
overloaded in the ostream class. The istream class overloads the >>
operator for the standard types [int, long, double, float, char, and
char *(string)] .
• For example, the statement, cin>>x; calls the appropriate >> operator
function for the istream cin defined in iostream.h. And uses it to
direct this input stream into the memory location represented by the
variable x.
• Similarly, the ostream class overloads the << operator, which allows the
statement, cout<<; to send the value of x to ostream cout for output.
• Actually, istream provides the generic code for formatting the data after it
is extracted from the input stream. Similarly, ostream provides the generic
code for formatting the data before it is inserted to the outputstream.
• Program:- Accept and display the information using extraction and
insertion operators.
#include<iostream.h>
using namespace std;
class info
{
private :
int roll;
char name[20];
public:
info()
{
roll = 0;
name[0] = ‘0’;
}
friend istream & operator >>(istream &, info&);
friend ostream & operator >>(ostream &, info&);
};
istream & operator >>(istream &s, info &d)
{
cout<<“Enter Rollno”; int main()
S>>d.roll; {
cout<<“Enter Name :”; info ob1;
S>>d.name; cin>>ob1;
return s; cout<<ob1;
} }
ostream & operator <<(ostream &s, info &d) Output :
{ Enter rollno : 101
S<<d.roll; Enter name : Prajakta
S<<d.name; 101 Prajakta.
return S;
}
Usage of ‘this’ Pointer :
• Every object in C++ has access to its own address through an
important pointer called ‘this’ pointer.
• In other words, ”The member functions of each and every object have
access to a pointer named ‘this’, which points to the object itself.”
• The ‘this’ pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the
invoking object.
• Friend functions do not have a ‘this’ pointer, because friends are not
members of a class. Only member functions have a ‘this’ pointer.
• ‘this’ is a pointer that points to the object for which the function was
called.
• ‘this’ pointer is predefined pointer variable within every class.
• ‘this’ pointer is a pointer pointing to the current object of specified
class. ‘this’ is a keyword in C++.
• Syntax :-
class_name *this;
• Every object has access to its own address through a pointer called
this. When a member function is called, ‘this’ pointer is automatically
passed as an implicit argument to that function.
• For example : The function call,
s.sample(); will set the pointer this to the address of the object s.
• One of the important application of “this” pointer is to return the
object to which it is pointing .
• For example : return *this;
• Inside a member function will return the object that invokes a
member function.
• Write a Program to class test having data members as name of a student and
marks. Accept and display information by using ‘this’ pointer.
#include<iostream.h> void display()
using namespace std; {
this->get();
class test cout<<“\n Name =” <<this->name;
{ cout<<“\n Marks = ”<<this->marks;
private : }
};
char name[40];
float marks; int main()
{
public : test t1,t2;
void get() t1.display();
{ t2.display();
return 0;
cout<<“\n Enter name & marks”; }
cin>>name>>marks; Output :
Enter name & marks :
} Prajakta 80
Name = Prajakta
Marks = 80
Type Conversion :
• Type Conversion is also known as Implicit Type Conversion.
• It is done by the compiler on its own.
• There is no external trigger required by the user to typecast a variable
from one type to another.
• This occurs when an expression contains vaiables of more than one
type. So, in those scenarios automatic type conversion takes place to
avoid loss of data.
• In automatic type conversion, all the data types present in the
expression are converted to data type of the variable with the largest
data type.
• For example:
short a = 2000;
int b;
b=a;
• Here, the value of ‘a’ has been promoted from short to int and we
have not had to specify any typecasting operator. This is known as a
standard conversion.
• Standard conversions affect fundamental data types, and allow
conversions such as the conversions between numerical types (short
to int, int to float, double to int…) , to or from bool, and some pointer
conversions.
• Some of these conversions may imply a loss of precision, which the
compiler can signal with a warning.
• This warning can be avoided with an explicit conversion.
• C++ Program for type conversion.
#include<iostream.h>
using namespace std;
int main()
{
int a = 9;
double b;
b=a;
cout<<“int =” <<a<<endl;
cout<<“double =” <<b<<endl;
}
Output:
int = 9;
double = 9;

You might also like