0% found this document useful (0 votes)
47 views

Chapter5 PDF

Constructors automatically initialize objects when they are created and have the same name as the class. Destructors automatically destroy objects before they go out of scope and are prefixed with a tilde (~). Copy constructors are used to initialize one object using another of the same class. Multiple constructors can be defined through overloading to allow initializing objects in different ways.

Uploaded by

Rosʜʌŋ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Chapter5 PDF

Constructors automatically initialize objects when they are created and have the same name as the class. Destructors automatically destroy objects before they go out of scope and are prefixed with a tilde (~). Copy constructors are used to initialize one object using another of the same class. Multiple constructors can be defined through overloading to allow initializing objects in different ways.

Uploaded by

Rosʜʌŋ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter 5

Constructors and Destructors

Constructor:
A ‘constructor’ is a special member function whose task is to automatically initialization of an
object of its class. It is special because its name is the same name of the same as the class name. The
constructor is invoked whenever an object of its associated class is created. It is called constructor
because it constructs the values of the data member of the class. The rules for writing constructor
functions or its characteristics are:
• A constructor name must be the same name as that of its class name.
• It is declared with no return type (not even void).
• It should have public or protected access within the class.
• They are invoked automatically when the objects are created.
• They cannot be inherited, though a derived class can call the base constructors.
• Like other C++ functions, they have default arguments.
• Constructors cannot be virtual, cannot refer to their addresses.
• An object with a constructor (or destructor) cannot be used as a member of a union.
• They make ‘implicit calls’ to the operator new and delete when dynamic memory allocation
is required.

Syntax:
class className
{
private:
………….
public:
className( ); //constructor
…………. };

className :: className( ) //body of the constructor


{ …………. }

An example:
class consTest
{ private:
int a;
public:
consTest() //constructor
{ a=100; }

void display()
{cout<<"The value of data is\t :"<<a; }
};

void main()
{
consTest obj1,obj2;
Prepared By:
Er.Dipesh Bista
obj1.display();
obj2.display(); }

Output: The value of the data is :100


The value of the data is :100
Here, the constructor consTest takes no arguments. This type of constructor is called default
constructor.

Parameterized constructors
The constructor consTest(), defined above, initialized the data member of all the objects to 100.
However, in practice it may be necessary to initialize the various data elements of different values
when they are created. C++ permits us to achieve this objective by passing arguments to the
constructor function when the objects are created. The constructors that can take arguments are
called parameterized constructors. A constructor may be defined with default arguments like
function. The default constructor and constructor with default arguments are different things.
Example
Program to demonstrate the passing of arguments to the constructor

class rectangle
{
private:
float length,breadth;
public:
rectangle(float l, float b)
{ length=l;
breadth=b; }

void area()
{ cout<<"\nThe area of rectangle is:"<<length*breadth; }
};

void main()
{
rectangle r1(10,20); //constructor call implicitly
rectangle r2=rectangle(20,30); //constructor call explicitly
r1.area();
r2.area();
}

Output Of The Program


The area of rectangle is:200
The area of rectangle is:600

Multiple constructors in a class (Overloaded Constructors)


When more than one constructor function defined in a class, then we say that the constructor is
overloaded.

#include <iostream.h>
#include <conio.h>
class rectangle
Prepared By:
Er.Dipesh Bista
{
private:
float length,breadth;
public:
rectangle() //constructor declared without argument
{ length=0;
breadth=0;
}

rectangle(float side) //constructor declared with one argument


{ length=side;
breadth=side;
}

rectangle(float l,float b) //constructor declared with two arguments


{ length=l;
breadth=b; }
void calculateArea()
{ cout<<"\nThe area is\t :"<<(length*breadth); }
};

int main()
{
rectangle r1; //call constructor rectangle()
rectangle r2(10); //call constructor rectangle(float side)
rectangle r3(10,30);//call constructor rectangle(float l, float b)
r1.calculateArea();
r2.calculateArea();
r3.calculateArea();
}

Output:
The area is :0
The area is : 100
The area is : 300

Copy constructors
Copy constructors are always used when the compiler has to create a temporary object of a class
object. The copy constructors are used when the initialization of an object is to be done by another
object of the same class.
The general format of the copy constructor is,
class_name(class_name &object)
e.g.
class copyConst
{
…..
public:
copyConst(copyConst &ob);
};

Example:
Prepared By:
Er.Dipesh Bista
class sample
{
int id;
public:
sample (int x) //constructor again defined with passing arguments
{ id=x; }

sample(sample & obj) //copy constructor


{ id=obj.id; } //copy in the value

void display()
{ cout<<id; }
};
void main()
{ sample ob1(100); // object a is created and initialized
sample ob2(ob1); // copy constructor called
sample ob3(ob2); // copy constructor called again
cout<<"\nId of ob1: ";
ob1.display();
cout<<"\nId of ob2: ";
ob2.display();
cout<<"\nId of ob3: ";
ob3.display();
}

Output:
Id of ob1: 100
Id of ob2: 100
Id of ob3: 100

Destructor
A ‘destructor’ as the name implies, is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose name is the same as the
class name but is preceded by a tilde (~). A destructor is a function that automatically executed
when an object is destroyed. Destructor functions get executed whenever an instance of the class to
which it belongs goes out of existence. The primary usage of the destructor is to release space on
the heap. A destructor function may be invoked explicitly. Rules for writing a destructor function
are:
• A destructor function name is the same as that of the class it belongs except that the first
character of the name must be tilde (~).
• It is declared with no return types (not even void) since it cannot ever return a value.
• It cannot be declared static.
• It takes no arguments and therefore cannot be overloaded.
• It should have public access in the class declaration.

Syntax:
~className()
{…..
…..}
Example:
Prepared By:
Er.Dipesh Bista
class desTest
{ private:
int a;
public:
desTest()
{ cout<<"\nI am within Constructor";
a=100; }

~desTest() Output:
{ cout<<"\nI am within Destructor";} I am within Constructor
Value of data is:100
void display() I am within Destructor
{cout<<"\nValue of data is:"<<a;}
};
void main()
{ desTest ob;
ob.display(); }

Another Example:
int count=0;
class alpha Output
{ Enter Main
public:
alpha() //constructor function declaration
Number of object created 1
{ count++;
cout<<"\nNumber of object created "<<count; }
Number of object created 2
Number of object created 3
~alpha() //destructor function declaration Number of object created 4
{
cout<<"\nNumber of object destroyed "<<count; Enter Block1
count--; }
}; Number of object created 5
void main() Number of object destroyed 5
{
cout<<"\n\n Enter Main \n"; Enter Block2
{
alpha a1,a2,a3,a4;//creation of the objects
{
Number of object created 5
cout<<"\n\nEnter Block1\n"; Number of object destroyed 5
alpha a5;
} Re-Enter Main
{
cout<<"\n\nEnter Block2\n"; Number of object destroyed 4
alpha a6; Number of object destroyed 3
} Number of object destroyed 2
cout<<"\n\nRe-Enter Main\n"; Number of object destroyed 1
}
}

As the objects are created and destroyed, they increase and decrease the count. Notice that after the
first group of objects is created, a5 is created, and then destroyed; a6 is created, and then destroyed.
Prepared By:
Er.Dipesh Bista
Finally, the rest of the rest of the objects are also destroyed. When the closing braces of a scope are
encountered, the destructors for each object in the scope are called. Note that the objects are
destroyed in the reverse order certain.

Prepared By:
Er.Dipesh Bista

You might also like