SlideShare a Scribd company logo
Constructors and Destructors
By
Nilesh Dalvi
Lecturer, Patkar‐Varde College.
Object oriented Programming
with C++
Constructor
• A constructor is a ‘special’ member function 
whose task is to initialize the objects of its 
class.
• It is special because its name is same as the 
class.
• It is called constructor because it constructs 
the value of data member.
• Constructor is invoked whenever an object
of its associated class is created.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• add a ;
• Creates the object ‘a’ of types 
add and initializes its data 
members m and n to zero.
• There is no need to write any 
statement to invoke the 
constructor function.
• A constructor  that accepts 
no parameter is called as a 
default constructor .
class add 
{ 
      int m, n ; 
   public : 
      add (void) ; 
      ‐‐‐‐‐‐ 
}; 
add :: add (void) 
{ 
   m = 0; n = 0; 
} 
Constructor
Characteristics of Constructor:
• They should be declared in the public section.
• They are invoked automatically when the objects 
are created.
• They do not have return types, not even void and 
they cannot return values.
• They cannot be inherited, though a derived class 
can call the base class constructor.
• Like other C++ functions, Constructors can have 
default arguments.
• Constructors can not be virtual.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Constructor:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Dynamic Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Default Constructor
• Default constructor is 
the constructor which 
doesn't take any 
argument. 
• It has no parameter.
• It is also called as zero‐
argument constructor.
#include<iostream> 
using namespace std; 
 
class Cube 
{ 
public: 
    int side; 
    Cube() 
    {   
        side=10; 
    } 
}; 
 
int main() 
{ 
    Cube c; 
    cout << c.side; 
    return 0; 
} 
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Parameterized Constructor
• It is also possible to create constructor with 
arguments and such constructors are called 
as parameterized constructors or 
constructor with arguments.
• For such constructors, it is necessary to pass 
values to the constructor when object is 
created.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Parameterized Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class area 
{ 
    int length,breadth; 
  public: 
    area(int l,int b)//parameterized constructor. 
    { 
        length = l; 
        breadth = b;         
    } 
    void display() 
    { 
        cout << "Length of rectangle is:" << length << endl; 
        cout << "Breadth of rectangle is: " << breadth << endl; 
        cout << "Area of rectangle is: " << length*breadth; 
    } 
}; 
Parameterized Constructor
• When a constructor has been parameterized, 
• area a; // may not work.
• We must pass initial value as arguments to the 
constructor function when an object is declared. 
This can be done by two ways:
– By calling the constructor explicitly.
– By calling the constructor implicitly.
• The following declaration illustrates above method:
area  a = area (5, 6);  // explicit call
area  a (5, 6);  // implicit call
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Parameterized Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
int main() 
{ 
    area a(8,7); 
    a.display(); 
 
    area c(10,5); 
    c.display(); 
 
    return 0; 
} 
Constructors with default arguments:
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include<iostream>
#include<cmath> 
using namespace std; 
  
class power 
{ 
    int num; 
    int power; 
    int ans; 
  public : 
    power (int n = 9, int p = 3); // declaration of constructor
                                  //with default arguments 
 
    void show () 
    { 
       cout <<"n"<<num <<" raise to "<<power <<" is " <<ans; 
    } 
}; 
 
power :: power (int n,int p ) 
{ 
    num = n; 
    power = p; 
    ans = pow (n, p); 
} 
int main( ) 
{ 
    power p1, p2(5); 
    p1.show (); 
    p2.show (); 
    return  0; 
} 
Copy Constructor
• The copy constructor is a constructor which 
creates an object by initializing it with an object of 
the same class, which has been created previously.
• The copy constructor is used to initialize one 
object from another of same type.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Copy Constructor
• Syntax:
class  abc
{
public:
abc (abc &);
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Copy Constructor
• Referencing operator (&) is used to define 
referencing variable.
• Ref. variable prepares an alternative (alias) name 
for previously defined variable.
• For Example:
int  qty = 10; // declared  and initialized.
int  & qt = qty;  // alias variable.
• Any change made in one of the variable causes 
change in both the variable.
qt = qt*2;       // contents of qt and qty will be 20.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Copy Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
// Class definition 
class TimeSlt 
{ 
    int Da, Mo, Ye; 
  public: 
    void Disply(); 
    TimeSlt(){}  
    TimeSlt(int D1,int M1,int Y1); // Constructor with parameters 
    TimeSlt(TimeSlt &); // Copy constructor 
}; 
void TimeSlt::Display() 
{ 
    cout<<Da<<" "<<Mo<<" "<<Ye<<endl; 
} 
TimeSlt::TimeSlt(int D1,int M1,int Y1) 
{ 
    Da = D1; 
    Mo = M1; 
    Ye = Y1; 
} 
TimeSlt::TimeSlt(TimeSlt &tmp) 
{ 
    cout<<"Data copied"<<endl; 
    Da = tmp.Da; 
    Mo = tmp.Mo; 
    Ye = tmp.Ye; 
} 
int main()
{ 
    TimeSlt T1(13,8,1990); 
    T1.Display(); 
    TimeSlt T2(T1); 
    T2.Dispaly(); 
    TimeSlt T3 = T1; 
    T3.Dispaly(); 
    TimeSlt T4; 
    T4 = T1; 
    T4.Dispaly(); 
    return 0; 
} 
Copy Constructor
TimeSlt T2 (T1);
• Object T2 is created with one object(T1),  the copy 
constructor is invoked and data members are initialized.
TimeSlt T3 = T1;
• Object T3 is created with assignment with object T1; copy 
constructor invoked, compilers copies all the members of 
object T1 to destination object T3 .
TimeSlt T4;
T4 = T1;
• Copy constructor is not executed, member‐to‐member of 
T1 are copied to object T4 , assignment statement assigns 
the values.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Constructor
• Like functions, it is also possible to overload constructors. 
• In previous examples, we declared single constructors 
without arguments and with all arguments.
• A class can contain more than one constructor. This is 
known as constructor overloading. 
• All constructors are defined with the same name as the 
class. 
• All the constructors contain different number of arguments.
• Depending upon number of arguments, the compiler 
executes appropriate constructor.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Overloading Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include<iostream> 
using namespace std; 
 
class perimeter 
{ 
    int l, b, p; 
   public: 
    perimeter () 
    { 
        cout << "n Enter the value of l and b"; 
        cin >> l >> b; 
    } 
    perimeter (int a) 
    { 
        l = b = a; 
    } 
    perimeter (int l1, int b1) 
    { 
        l = l1; 
        b = b1; 
    } 
    perimeter (perimeter &peri) 
    { 
        l = peri.l; 
        b = peri.b; 
    } 
    void calculate (void);     
}; 
Overloading Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
void perimeter :: calculate (void)
{ 
    p = 2* (l + b) 
    cout << p; 
} 
int main () 
{ 
 
    perimeter obj, obj1 (2), obj2 (2, 3); 
 
    cout<<"n perimeter of rectangle is "; 
    obj. Calculate (); 
 
    cout<<"n perimeter of square is "; 
    obj1.calculate (); 
 
    cout<<"n perimeter of rectangle is "; 
    obj2.calculate (); 
 
    cout<<"n perimeter of rectangle is "; 
    perimeter obj3 (obj2); 
    obj3.calculate (); 
 
    return 0; 
} 
Dynamic Constructor
• The constructors 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.
• Allocation of memory to objects at the time of 
their construction is known as dynamic 
construction of objects.
• The memory is created with the help of the new
operator.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Dynamic Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
#include <string>
using namespace std;
class str
{
char *name;
int len;
public:
str()
{
len = 0;
name = new char[len + 1];
}
str(char *s)
{
len = strlen(s);
name = new char[len + 1];
strcpy(name,s);
}
void show()
{
cout<<"NAME IS:->"<<name<<endl;
}
void join(str a, str b);
};
Dynamic Constructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
void str :: join(str a, str b)
{
len = a.len + b.len;
name = new char[len + 1];
strcpy(name, a.name);
strcat(name, b.name);
}
int main()
{
char *first="OOPS";
str n1(first),n2("WITH"),n3("C++"),n4,n5;
n4.join(n1,n2);
n5.join(n4,n3);
n1.show();
n2.show();
n3.show();
n4.show();
n5.show();
return 0;
}
Destructor
• Destructor is also a ‘special’ member 
function like constructor.
• Destructors destroy the class objects created 
by constructors. 
• The destructors have the same name as their 
class, preceded by a tilde (~).
• It is not possible to define more than one 
destructor. 
• For example : ~Circle();
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Destructor
• The destructor is only one way to destroy the 
object.
• They cannot be overloaded.
• A destructor neither requires any argument
nor returns any value.
• It is automatically called when object goes 
out of scope. 
• Destructor releases memory space occupied 
by the objects.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Destructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include<iostream>
using namespace std;
class Circle //specify a class
{
private :
double radius; //class data members
public:
Circle() //default constructor
{
radius = 0;
}
Circle(double r) //parameterized constructor
{
radius = r;
}
Circle(Circle &t) //copy constructor
{
radius = t.radius;
}
void setRadius(double r); //function to set data
double getArea();
~Circle() //destructor
{}
};
Destructor
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
void Circle :: setRadius(double r) //function to set data
{
radius = r;
}
double Circle :: getArea()
{
return 3.14 * radius * radius;
}
int main()
{
Circle c1; //defalut constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Circle c3(c2); //copy constructor invoked
cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
c1.setRadius (1.2);
cout << c1.getArea()<<endl;
return 0;
}
Const Member function
• The member functions of class can be declared  as 
constant using const keyword.
• The constant function cannot modify any data in 
the class.
• The const keyword is suffixed to the function 
declaration as well as in function definition.
• If these functions attempt to change the data, 
compiler will generate an error message.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Const Member function
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
class ABC
{
int c;
public:
void show(int a, int b) const
{
c = a + b;
cout << " a + b ::" <<c;
}
};
int main()
{
const ABC x;
x.show (5, 7);
return 0;
}
Const Member function
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
class ABC
{
int c;
public:
void show(int a, int b) const
{
//c = a + b;
cout << " a + b ::" <<a + b;
}
};
int main()
{
const ABC x;
x.show (5, 7);
return 0;
}
Const Objects
• Like constant member function, we can make the object
constant by the keyword const.
• Only constructor can initialize data member variables of 
constant objects.
• The data member of constant objects can only be read and 
any effect to alter values of variables will generate an error.
• The data member of constant objects are also called as a 
read‐only data member.
• The const‐objects can access only const‐functions.
• If constant objects tries to invoke a non‐member function, 
an error message will be displayed.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Const Objects
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
class ABC
{
int a;
public:
ABC(int m)
{
a = m;
}
void show() const
{
cout << "a = " << a <<endl;
}
};
Const Objects
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
int main()
{
const ABC x(5);
x.show ();
return 0;
}
Nilesh Dalvi, Lecturer@Patkar-Varde
College, Goregaon(W).
To be continued…..

More Related Content

What's hot

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
sandeep54552
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Ramish Suleman
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Pointer in c
Pointer in cPointer in c
Pointer in c
lavanya marichamy
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
University of Madras
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Access specifier
Access specifierAccess specifier
Access specifier
zindadili
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
Amit Trivedi
 

What's hot (20)

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
This pointer
This pointerThis pointer
This pointer
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 

Viewers also liked

Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
Learn By Watch
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
Ashita Agrawal
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
KV(AFS) Utarlai, Barmer (Rajasthan)
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Hitesh Kumar
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Saharsh Anand
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
OOP: Class Hierarchies
OOP: Class HierarchiesOOP: Class Hierarchies
OOP: Class HierarchiesAtit Patumvan
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nilesh Dalvi
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
Nilesh Dalvi
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
Amresh Raj
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
Nilesh Dalvi
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Constructor overloading in C++
Constructor overloading in C++Constructor overloading in C++
Constructor overloading in C++
Learn By Watch
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
Ye Win
 

Viewers also liked (20)

Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
OOP: Class Hierarchies
OOP: Class HierarchiesOOP: Class Hierarchies
OOP: Class Hierarchies
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Constructor overloading in C++
Constructor overloading in C++Constructor overloading in C++
Constructor overloading in C++
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 

Similar to Constructors and destructors

constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
nivedita murugan
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
rajshreemuthiah
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
C++ training
C++ training C++ training
C++ training
PL Sharma
 
C++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversionC++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversion
Hashni T
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptx
KavitaHegde4
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdf
KavitaHegde4
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Sunipa Bera
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Nilesh Dalvi
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
Michael Heron
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdf
MadnessKnight
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
Abbas Ajmal
 
C++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxC++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptx
sasukeman
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
DSMS Group of Institutes
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 

Similar to Constructors and destructors (20)

constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
C++ training
C++ training C++ training
C++ training
 
C++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversionC++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversion
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptx
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdf
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdf
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
C++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxC++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptx
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 

More from Nilesh Dalvi

13. Queue
13. Queue13. Queue
13. Queue
Nilesh Dalvi
 
12. Stack
12. Stack12. Stack
12. Stack
Nilesh Dalvi
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
Nilesh Dalvi
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
Nilesh Dalvi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
8. String
8. String8. String
8. String
Nilesh Dalvi
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
Nilesh Dalvi
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
Nilesh Dalvi
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh Dalvi
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
Nilesh Dalvi
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
Nilesh Dalvi
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
Nilesh Dalvi
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
Nilesh Dalvi
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
Strings
StringsStrings
Strings
Nilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 

More from Nilesh Dalvi (19)

13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
8. String
8. String8. String
8. String
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Strings
StringsStrings
Strings
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Recently uploaded

Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Constructors and destructors

  • 2. Constructor • A constructor is a ‘special’ member function  whose task is to initialize the objects of its  class. • It is special because its name is same as the  class. • It is called constructor because it constructs  the value of data member. • Constructor is invoked whenever an object of its associated class is created. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). • add a ; • Creates the object ‘a’ of types  add and initializes its data  members m and n to zero. • There is no need to write any  statement to invoke the  constructor function. • A constructor  that accepts  no parameter is called as a  default constructor . class add  {        int m, n ;     public :        add (void) ;        ‐‐‐‐‐‐  };  add :: add (void)  {     m = 0; n = 0;  } 
  • 4. Constructor Characteristics of Constructor: • They should be declared in the public section. • They are invoked automatically when the objects  are created. • They do not have return types, not even void and  they cannot return values. • They cannot be inherited, though a derived class  can call the base class constructor. • Like other C++ functions, Constructors can have  default arguments. • Constructors can not be virtual. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5. Types of Constructor: 1. Default Constructor 2. Parameterized Constructor 3. Copy Constructor 4. Dynamic Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 6. Default Constructor • Default constructor is  the constructor which  doesn't take any  argument.  • It has no parameter. • It is also called as zero‐ argument constructor. #include<iostream>  using namespace std;    class Cube  {  public:      int side;      Cube()      {            side=10;      }  };    int main()  {      Cube c;      cout << c.side;      return 0;  }  Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7. Parameterized Constructor • It is also possible to create constructor with  arguments and such constructors are called  as parameterized constructors or  constructor with arguments. • For such constructors, it is necessary to pass  values to the constructor when object is  created. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8. Parameterized Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class area  {      int length,breadth;    public:      area(int l,int b)//parameterized constructor.      {          length = l;          breadth = b;              }      void display()      {          cout << "Length of rectangle is:" << length << endl;          cout << "Breadth of rectangle is: " << breadth << endl;          cout << "Area of rectangle is: " << length*breadth;      }  }; 
  • 9. Parameterized Constructor • When a constructor has been parameterized,  • area a; // may not work. • We must pass initial value as arguments to the  constructor function when an object is declared.  This can be done by two ways: – By calling the constructor explicitly. – By calling the constructor implicitly. • The following declaration illustrates above method: area  a = area (5, 6);  // explicit call area  a (5, 6);  // implicit call Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 10. Parameterized Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). int main()  {      area a(8,7);      a.display();        area c(10,5);      c.display();        return 0;  } 
  • 11. Constructors with default arguments: Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include<iostream> #include<cmath>  using namespace std;     class power  {      int num;      int power;      int ans;    public :      power (int n = 9, int p = 3); // declaration of constructor                                   //with default arguments        void show ()      {         cout <<"n"<<num <<" raise to "<<power <<" is " <<ans;      }  };    power :: power (int n,int p )  {      num = n;      power = p;      ans = pow (n, p);  }  int main( )  {      power p1, p2(5);      p1.show ();      p2.show ();      return  0;  } 
  • 12. Copy Constructor • The copy constructor is a constructor which  creates an object by initializing it with an object of  the same class, which has been created previously. • The copy constructor is used to initialize one  object from another of same type. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 14. Copy Constructor • Referencing operator (&) is used to define  referencing variable. • Ref. variable prepares an alternative (alias) name  for previously defined variable. • For Example: int  qty = 10; // declared  and initialized. int  & qt = qty;  // alias variable. • Any change made in one of the variable causes  change in both the variable. qt = qt*2;       // contents of qt and qty will be 20. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 15. Copy Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). // Class definition  class TimeSlt  {      int Da, Mo, Ye;    public:      void Disply();      TimeSlt(){}       TimeSlt(int D1,int M1,int Y1); // Constructor with parameters      TimeSlt(TimeSlt &); // Copy constructor  };  void TimeSlt::Display()  {      cout<<Da<<" "<<Mo<<" "<<Ye<<endl;  }  TimeSlt::TimeSlt(int D1,int M1,int Y1)  {      Da = D1;      Mo = M1;      Ye = Y1;  }  TimeSlt::TimeSlt(TimeSlt &tmp)  {      cout<<"Data copied"<<endl;      Da = tmp.Da;      Mo = tmp.Mo;      Ye = tmp.Ye;  }  int main() {      TimeSlt T1(13,8,1990);      T1.Display();      TimeSlt T2(T1);      T2.Dispaly();      TimeSlt T3 = T1;      T3.Dispaly();      TimeSlt T4;      T4 = T1;      T4.Dispaly();      return 0;  } 
  • 16. Copy Constructor TimeSlt T2 (T1); • Object T2 is created with one object(T1),  the copy  constructor is invoked and data members are initialized. TimeSlt T3 = T1; • Object T3 is created with assignment with object T1; copy  constructor invoked, compilers copies all the members of  object T1 to destination object T3 . TimeSlt T4; T4 = T1; • Copy constructor is not executed, member‐to‐member of  T1 are copied to object T4 , assignment statement assigns  the values. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 17. Overloading Constructor • Like functions, it is also possible to overload constructors.  • In previous examples, we declared single constructors  without arguments and with all arguments. • A class can contain more than one constructor. This is  known as constructor overloading.  • All constructors are defined with the same name as the  class.  • All the constructors contain different number of arguments. • Depending upon number of arguments, the compiler  executes appropriate constructor. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 18. Overloading Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include<iostream>  using namespace std;    class perimeter  {      int l, b, p;     public:      perimeter ()      {          cout << "n Enter the value of l and b";          cin >> l >> b;      }      perimeter (int a)      {          l = b = a;      }      perimeter (int l1, int b1)      {          l = l1;          b = b1;      }      perimeter (perimeter &peri)      {          l = peri.l;          b = peri.b;      }      void calculate (void);      }; 
  • 19. Overloading Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). void perimeter :: calculate (void) {      p = 2* (l + b)      cout << p;  }  int main ()  {        perimeter obj, obj1 (2), obj2 (2, 3);        cout<<"n perimeter of rectangle is ";      obj. Calculate ();        cout<<"n perimeter of square is ";      obj1.calculate ();        cout<<"n perimeter of rectangle is ";      obj2.calculate ();        cout<<"n perimeter of rectangle is ";      perimeter obj3 (obj2);      obj3.calculate ();        return 0;  } 
  • 20. Dynamic Constructor • The constructors 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. • Allocation of memory to objects at the time of  their construction is known as dynamic  construction of objects. • The memory is created with the help of the new operator. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 21. Dynamic Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> #include <string> using namespace std; class str { char *name; int len; public: str() { len = 0; name = new char[len + 1]; } str(char *s) { len = strlen(s); name = new char[len + 1]; strcpy(name,s); } void show() { cout<<"NAME IS:->"<<name<<endl; } void join(str a, str b); };
  • 22. Dynamic Constructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). void str :: join(str a, str b) { len = a.len + b.len; name = new char[len + 1]; strcpy(name, a.name); strcat(name, b.name); } int main() { char *first="OOPS"; str n1(first),n2("WITH"),n3("C++"),n4,n5; n4.join(n1,n2); n5.join(n4,n3); n1.show(); n2.show(); n3.show(); n4.show(); n5.show(); return 0; }
  • 23. Destructor • Destructor is also a ‘special’ member  function like constructor. • Destructors destroy the class objects created  by constructors.  • The destructors have the same name as their  class, preceded by a tilde (~). • It is not possible to define more than one  destructor.  • For example : ~Circle(); Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 24. Destructor • The destructor is only one way to destroy the  object. • They cannot be overloaded. • A destructor neither requires any argument nor returns any value. • It is automatically called when object goes  out of scope.  • Destructor releases memory space occupied  by the objects. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 25. Destructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include<iostream> using namespace std; class Circle //specify a class { private : double radius; //class data members public: Circle() //default constructor { radius = 0; } Circle(double r) //parameterized constructor { radius = r; } Circle(Circle &t) //copy constructor { radius = t.radius; } void setRadius(double r); //function to set data double getArea(); ~Circle() //destructor {} };
  • 26. Destructor Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). void Circle :: setRadius(double r) //function to set data { radius = r; } double Circle :: getArea() { return 3.14 * radius * radius; } int main() { Circle c1; //defalut constructor invoked Circle c2(2.5); //parmeterized constructor invoked Circle c3(c2); //copy constructor invoked cout << c1.getArea()<<endl; cout << c2.getArea()<<endl; cout << c3.getArea()<<endl; c1.setRadius (1.2); cout << c1.getArea()<<endl; return 0; }
  • 27. Const Member function • The member functions of class can be declared  as  constant using const keyword. • The constant function cannot modify any data in  the class. • The const keyword is suffixed to the function  declaration as well as in function definition. • If these functions attempt to change the data,  compiler will generate an error message. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 28. Const Member function Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; class ABC { int c; public: void show(int a, int b) const { c = a + b; cout << " a + b ::" <<c; } }; int main() { const ABC x; x.show (5, 7); return 0; }
  • 29. Const Member function Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; class ABC { int c; public: void show(int a, int b) const { //c = a + b; cout << " a + b ::" <<a + b; } }; int main() { const ABC x; x.show (5, 7); return 0; }
  • 30. Const Objects • Like constant member function, we can make the object constant by the keyword const. • Only constructor can initialize data member variables of  constant objects. • The data member of constant objects can only be read and  any effect to alter values of variables will generate an error. • The data member of constant objects are also called as a  read‐only data member. • The const‐objects can access only const‐functions. • If constant objects tries to invoke a non‐member function,  an error message will be displayed. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 31. Const Objects Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; class ABC { int a; public: ABC(int m) { a = m; } void show() const { cout << "a = " << a <<endl; } };
  • 32. Const Objects Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). int main() { const ABC x(5); x.show (); return 0; }
  • 33. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). To be continued…..