CH 4-Constructor & Destructor
CH 4-Constructor & Destructor
}
• 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]
1 dummy
2
y
3
30 q
• 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
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.
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
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
};
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;