Object Oriented
Programming with C++
Unit-4
Constructors
and Destructors
What is constructor ?
A constructor is a block of code which is,
similar to member function
has same name as class name
called automatically when object of class created
A constructor is used to initialize the objects of class as soon as the
object is created.
Constructor
class car class car
{ Same {
private: name as private:
float mileage; float mileage;
public: class name public:
void setdata() car()
{ Similar to {
cin>>mileage; member cin>>mileage;
} function }
}; };
int main() int main()
Called
{ {
automatically
car c1;
c1,c2; car c1,c2;
c1;
on creation
c1.setdata();
of object
c2.setdata();
} }
Properties of Constructor
▪ Constructor should be declared in public class car
{
section because private constructor cannot private:
be invoked outside the class so they are float mileage;
useless. public:
car()
▪ Constructors do not have return types and {
they cannot return values, not even void. cin>>mileage;
}
};
▪ Constructors cannot be inherited, even though a derived class can
call the base class constructor.
▪ Constructors cannot be virtual.
▪ They make implicit calls to the operators new and delete when
memory allocation is required.
Constructor (Cont…)
class Rectangle
{
int width,height;
public:
Rectangle(){
width=5;
height=6;
cout<<”Constructor Called”;
}
};
int main()
{
Rectangle r1;
return 0;
}
Types of Constructors
Types of Constructors
1) Default constructor
2) Parameterized constructor
3) Copy constructor
1) Default Constructor
▪ Default constructor is the one which invokes by default when
object of the class is created.
▪ It is generally used to initialize the default value of the data
members.
▪ It is also called no argument constructor.
class demo{ int main()
int m,n; { Object d1
public: demo d1;
demo() m n
}
{ 10 10
m=n=10;
}
};
Program Constructor
class Area int main(){
{ Area A1;
private: A1.Calculate();
int length, breadth; Area A2;
public: A2.Calculate();
Area(){ return 0;
length=5; }
breadth=2;
}
void Calculate(){
cout<<"\narea="<<length * breadth;
} A1 A2
};
length breadth length breadth
5 2 5 2
2) Parameterized Constructor
▪ Constructors that can take arguments are called parameterized
constructors.
▪ Sometimes it is necessary to initialize the various data elements of
different objects with different values when they are created.
▪ We can achieve this objective by passing arguments to the
constructor function when the objects are created.
Parameterized Constructor
▪ Constructors that can take arguments are called parameterized
constructors.
class demo
{
int m,n;
public:
demo(int x,int y){ //Parameterized Constructor
m=x;
n=y;
cout<<“Constructor Called“;
}
};
int main() d1
{ m n
demo d1(5,6);
} 5 6
Program Parameterized Constructor
▪ Create a class Distance having data members feet and inch.
Create parameterized constructor to initialize members feet and
inch.
3) Copy Constructor
▪ A copy constructor is used to declare and initialize an object from
another object using an object as argument.
▪ For example:
demo(demo &d); //declaration
demo d2(d1); //copy object
OR demo d2=d1; //copy object
▪ Constructor which accepts a reference to its own class as a
parameter is called copy constructor.
3) Copy Constructor
▪ A copy constructor is used to initialize an object
from another object
using an object as argument.
▪ A Parameterized constructor which accepts a reference to its own
class as a parameter is called copy constructor.
Copy Constructor
class demo int main()
{ {
int m, n; demo obj1(5,6);
public: demo obj2(obj1);
demo(int x,int y){ demo obj2 = obj1;
m=x; }
n=y;
obj1
obj1 or x
cout<<"Parameterized Constructor";
} m n
demo(demo &x){
5 6
m = x.m;
n = x.n;
obj2
cout<<"Copy Constructor";
} m n
}; 5 6
Program: Types of Constructor
▪ Create a class Rectangle having data members length and
width. Demonstrate default, parameterized and copy
constructor to initialize members.
Program: Types of Constructor
class rectangle{
int length, width; This is constructor
public: overloading
rectangle(){ // Default constructor
length=0;
width=0;
}
rectangle(int x, int y){// Parameterized
constructor
length = x;
width = y;
}
rectangle(rectangle &_r){ // Copy constructor
length = _r.length;
width = _r.width;
}
};
Program: Types of Constructor (Cont…)
int main()
{
rectangle r1; // Invokes default constructor
rectangle r2(10,20); // Invokes parameterized
constructor
rectangle r3(r2); // Invokes copy constructor
}
Destructor
Destructor class car
{
• Destructor is used to destroy the objects float mileage;
public:
that have been created by a constructor. car(){
• The syntax for destructor is same as that cin>>mileage;
}
for the constructor,
– the class name is used for the name of ~car(){
cout<<" destructor";
destructor, }
– with a tilde (~) sign as prefix to it.
};
Destructor
▪ never takes any argument nor it returns any value nor it has return
type.
▪ is invoked automatically by the complier upon exit from the
program.
▪ should be declared in the public section.
Program: Destructor
class rectangle int main()
{ {
int length, width; rectangle x;
public: // default
rectangle(){ //Constructor constructor is
length=0; called
width=0; }
cout<<”Constructor Called”;
}
~rectangle() //Destructor
{
cout<<”Destructor Called”;
}
// other functions for reading, writing and
processing can be written here
};
Program: Destructor
class Marks{ int main( )
public: {
int maths; Marks m1;
int science; Marks m2;
//constructor return 0;
Marks() { }
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
Operator Overloading
Operator Overloading
int a=5, b=10,c; Operator + performs
c = a + b; addition of
integer operands a, b
time t1,t2,t3; Operator + performs
t3 = t1 + t2; addition of
objects of type time
string str1=“Hello” Operator + concatenates
string str2=“Good Day”; two strings str1,str2
string str3;
str3 = str1 + str2;
Operator overloading
▪ Function overloading allow you to use same function name for
different definition.
▪ Operator overloading extends the overloading concept to
operators, letting you assign multiple meanings to C++ operators
▪ Operator overloading giving the normal C++ operators such as +, *
and == additional meanings when they are applied with user
defined data types.
Operator Purpose
Some of C++ Operators * As pointer, As multiplication
are already overloaded As insertion, As bitwise shift left
<<
& As reference, As bitwise AND
Operator Overloading
int a=5, b=10,c;
c = a + b;
Operator + performs addition of integer
operands a, b
class time
{
int hour, minute;
}; Operator + performs addition of objects of
time t1,t2,t3; type time t1,t2
t3 = t1 + t2;
string str1=“Hello”,str2=“Good Day”;
str1 + str2; Operator + concatenates two strings
str1,str2
Operator Overloading
▪ Specifying more than one definition for an operator in the same
scope, is called operator overloading.
▪ You can overload operators by creating “operator functions”.
Syntax:
return-type operator op-symbol(argument-list)
{
// statements
} Keyword substitute the operator
Example:
void operator + (arguments);
int operator - (arguments);
class-name operator / (arguments);
float operator * (arguments);
Overloading Binary operator + int main()
class complex{ {
int real,imag; complex c1(4,6),c2(7,9);
public: complex c3;
complex(){ c3 = c1 + c2;
real=0; imag=0; c1.disp();
} c2.disp();
complex(int x,int y){ c3.disp();
real=x; imag=y; return 0;
} }
void disp(){
cout<<"\nreal value="<<real<<endl;
cout<<"imag value="<<imag<<endl;
}
complex operator + (complex);
};
complex complex::operator + (complex c){
complex tmp;
tmp.real = real + c.real; Similar to function call
tmp.imag = imag + c.imag;
return tmp;
c3=c1.operator +(c2);
}
Binary Operator Arguments
result = obj1.operator symbol (obj2);//function notation
result = obj1 symbol obj2; //operator notation
complex operator + (complex x)
{
complex tmp;
tmp.real = real + x.real;
tmp.imag = imag + x.imag;
return tmp;
}
result = obj1.display();
void display()
{
cout<<"Real="<<real;
cout<<"Imaginary="<<imag;
}
Operator Overloading
▪ Operator overloading is compile time polymorphism.
▪ You can overload most of the built-in operators available in C++.
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Operator Overloading using
Friend Function
Invoke Friend Function in operator overloading
result = operator symbol (obj1,obj2);//function notation
result = obj1 symbol obj2; //operator notation
friend complex operator +(complex c1,complex c2)
{
complex tmp;
tmp.r=c1.r+c2.r;
tmp.i=c1.i+c2.i;
return tmp;
}
int main()
{
complex c1(4,7),c2(5,8);
complex c3;
c3 = c1 + c2;
c3 = operator +(c1,c2);
}
Overloading Binary operator ==
class complex{ int main()
int r,i; {
public: complex c1(5,3),c2(5,3);
complex(){ if(c1==c2)
r=i=0;} cout<<"objects are equal";
complex(int x,int y){ else
r=x; cout<<"objects are not equal";
i=y;} return 0;
void display(){ }
cout<<"\nreal="<<r<<endl;
cout<<"imag="<<i<<endl;}
int operator==(complex);
};
int complex::operator ==(complex c){
if(r==c.r && i==c.i)
return 1;
else
return 0;}
Overloading Unary Operator
Overloading Unary operator − int main()
class space { {
int x,y,z; space s1(5,4,3);
public: s1.display();
space(){ -s1;
x=y=z=0;} s1.display();
space(int a, int b,int c){ return 0;
x=a; y=b; z=c; } }
void display(){
cout<<"\nx="<<x<<",y="<<y<<",z="<<z;
}
void operator-();
};
void space::operator-() {
x=-x;
y=-y;
z=-z;
}
Overloading Unary operator −− int main()
class space { {
int x,y,z; space s1(5,4,3);
public: s1.display();
space(){ --s1;
x=y=z=0;} s1.display();
space(int a, int b,int c){ return 0;
x=a; y=b; z=c; } }
void display(){
cout<<"\nx="<<x<<",y="<<y<<",z="<<z;
}
void operator--();
};
void space::operator--() {
x--;
y--;
z--;
}
Overloading Prefix and Postfix operator
class demo
{ int main()
int m; {
public: demo d1(5);
demo(){ m = 0;} ++d1;
demo(int x) d1++;
{ }
m = x;
}
void operator ++()
{
++m;
cout<<"Pre Increment="<<m;
}
void operator ++(int)
{
m++;
cout<<"Post Increment="<<m;
}
};
Invoking Operator Function
▪ Binary operator
operand1 symbol operand2
▪ Unary operator
operand symbol
symbol operand
▪ Binary operator using friend function
operator symbol (operand1,operand2)
▪ Unary operator using friend function
operator symbol (operand)
Rules for operator overloading
▪ Only existing operator can be overloaded.
▪ The overloaded operator must have at least one operand that is
user defined type.
▪ We cannot change the basic meaning and syntax of an operator.
Rules for operator overloading (Cont…)
▪ When using binary operators overloaded through a member
function, the left hand operand must be an object of the relevant
class.
▪ We cannot overload following operators.
Operator Name
. and .* Class member access operator
:: Scope Resolution Operator
sizeof() Size Operator
?: Conditional Operator
Type Conversion
Type Conversion
F = C * 9/5 + 32 If different data types are mixed in expression, C++
applies automatic type conversion as per certain
rules.
float int
int a; a = 10;
float b = 10.54; ▪ float is converted to integer automatically
a = b; by complier.
▪ basic to basic type conversion.
integer float
(Basic) (Basic)
▪ An assignment operator causes automatic type conversion.
▪ The data type to the right side of assignment operator is automatically
converted data type of the variable on the left.
Type Conversion
Time t1;
int m;
m = t1;
integer Time ▪ class type will not be converted to
(Basic) (Class) basic type OR basic type will not
be converted class type
t1 = m; automatically.
Time integer
(Class) (Basic)
Type Conversion
▪ C++ provides mechanism to perform automatic type conversion if
all variable are of basic type.
▪ For user defined data type programmers have to convert it by
using constructor or by using casting operator.
▪ Three type of situation arise in user defined data type conversion.
1. Basic type to Class type (Using Constructors)
2. Class type to Basic type (Using Casting Operator Function)
3. Class type to Class type (Using Constructors & Casting
Operator Functions)
(1) Basic to class type conversion
▪ Basic to class type can be achieved using constructor.
class sample
int main()
{
int a; {
public: int m=10;
sample s;
sample(){}
sample(int x){ s = m;
s.disp();
a=x;
} return 0;
void disp(){ }
cout<<"The value of a="<<a;
}
};
(2) Class to basic type conversion
▪ The Class type to Basic type conversion is done using casting operator
function.
▪ The casting operator function should satisfy the following conditions.
1. It must be a class member.
2. It must not mention a return type.
3. It must not have any arguments.
Syntax:
operator destinationtype()
{
....
return
}
Program: Class to basic type conversion
class sample int main()
{ {
float a; sample S;
public: int y= S;//Class to Basic
sample() conversion
{ cout<<"The value of y="<<y;
a=10.23; return 0;
} }
operator int() //Casting operator
function
{ Explicit type conversion
int x; y = int (S);
x=a;
return x;
Automatic type conversion
} y = S;
};
Program: Class to basic type conversion
class vector{ int main()
int a[5]; {
public: vector v;
vector(){ int len;
for(int i=0;i<5;i++) len = v;
a[i] = i*2; cout<<“Length of V="<<len;
} return 0;
operator int(); }
};
vector:: operator int() {
int sum=0;
for(int i=0;i<5;i++)
sum = sum + a[i];
return sum;}
(3) Class type to Class type
▪ It can be achieved by two ways
1. Using constructor
2. Using casting operator function
class alpha
{
Program: Class type to Class type
int commona;
public: class beta
alpha(){} {
alpha(int x) int commonb;
{ public:
commona = x; beta(){}
} beta(int x)
int getvalue() {
{ commonb = x;
return commona; }
} beta(alpha temp) //Constructor
}; {
commonb = temp.getvalue();
int main() }
{ operator alpha() //operator function
alpha obja(10); {
beta objb(obja); return alpha(commonb);
beta objb(20); }
obja = objb; };
}
class stock2 ;
class stock1{ Program: Type Conversion
int code , item ;
float price ;
public :
stock1 ( int a , int b , int c ) {
code = a ; item = b ; price = c ;
}
void disp () {
cout << " code " << code << " \n " ;
cout << " items " << item << " \n " ;
cout << " price per item Rs. " << price << " \n " ;
}
int getcode (){ return code; }
int getitem (){ return item ; }
int getprice (){ return price ; }
operator float () {
return ( item*price ) ;
}
};
class stock2{
int code ;
Program: Type Conversion
float val ;
public :
stock2 () {
code = 0; val = 0 ;
}
stock2( int x , float y ){
code = x ; val = y ;
}
void disp () {
cout << " code " << code << " \n " ;
cout << " total value Rs. " << val << " \n " ;
}
stock2( stock1 p ) {
code = p.getcode() ;
val = p.getitem() * p.getprice() ;
}
};
int main() Program: Type Conversion
{
stock1 i1 ( 101 , 10 ,125.0 ) ;
stock2 i2 ;
float tot_val = i1;
i2 = i1 ;
cout << " Stock Details : Stock 1 type " << " \n " ;
i1.disp ();
cout << " Stock Value " << " - " ;
cout << tot_val << " \n " ;
cout << " Stock Details : Stock 2 type " << " \n " ;
i2.disp () ;
return 0 ;
}
Thank You