SlideShare a Scribd company logo
1 of 33
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

Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods javaPadma Kannan
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++Bhavik Vashi
 

What's hot (20)

Java constructors
Java constructorsJava constructors
Java constructors
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Structure in C
Structure in CStructure in C
Structure in C
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 

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
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
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 javaHitesh 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 & objectsRai University
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh 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
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cppNilesh Dalvi
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
Constructor overloading in C++
Constructor overloading in C++Constructor overloading in C++
Constructor overloading in C++Learn By Watch
 

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
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
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++
 

Similar to Constructors and destructors

Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructorrajshreemuthiah
 
[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 TypesMuhammad 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 conversionHashni T
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfKavitaHegde4
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxKavitaHegde4
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorSunipa Bera
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
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].pdfLadallaRajKumar
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdfMadnessKnight
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval 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 2Abbas Ajmal
 
C++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxC++ Constructor and Destructors.pptx
C++ Constructor and Destructors.pptxsasukeman
 
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 NotesDigitalDsms
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 

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.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdf
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptx
 
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
 
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
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 

More from Nilesh Dalvi

10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to DatastructureNilesh Dalvi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and IntefacesNilesh Dalvi
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and MethodsNilesh Dalvi
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and VariablesNilesh Dalvi
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of JavaNilesh Dalvi
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryNilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 

More from Nilesh Dalvi (18)

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
 
Strings
StringsStrings
Strings
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

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…..