SlideShare uma empresa Scribd logo
1 de 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…..

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
This pointer
This pointerThis pointer
This pointer
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 

Destaque

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 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
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 

Mais de 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
 

Último

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
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
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
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
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Último (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.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
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
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
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

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