You are on page 1of 32

CONSTRUCTORS

&
DESTRUCTOR
PDPU
Introduction …
We write
int i = 0; // valid statement
but
We cannot initialize variables directly when we
define any class.
Why?
The memory allocation would be done only when
we create objects from this class.

2
Introduction …
Try following code & see the error.
class circle
{
int r = 0;
Public:
float area();
};
// Error: cannot initialize class member here.
WHY: No memory is allocated when you define a
class. 3
Introduction …
We have to pass value via function to initialize
variable of a class.

This passed value in turn is assigned to member


variable.

Look at the following example…

4
LOOK AT setradius()…
class circle
{
private:
int radius;
float area;
public:
void setradius(int r)
{
radius = r ;
};
float calc_area(void);
}; 5
Constructors …
C++ provides a special member function called
constructor that enables an object to initialize
itself when it is created.
Also known as automatic initialization of objects.

First, look at the example & then syntax.

6
Constructors… example …
class circle public:
{ circle()
private: {
int radius; radius = 0;
float area;
};
float calc_area (float);
};

See program constr1.cpp


7
Declaring constructors …
class <class-name>
{

public:
<class-name>(void); // constructor declared.

};
Note: Name of the class is the name of
constructor.

8
Defining constructors …
<class-name> :: <class-name>()
{

};

Note: Constructors can be defined inside or outside


the class.

9
Few Points Before We Move Further …

The constructor is invoked (called) whenever an


object of its associated class is created.
The variables of the object created by class will be
initialized automatically when the object is
created.
No need to write any statement to invoke the
constructor function.

10
Few Points Before We Move Further …

Constructors having no parameter is known as


default constructors.
Constructor function should be defined in public
section.
They do not have return types, not even void. See
example
They cannot return values.
They can have default arguments.
We cannot refer to their addresses.
11
Parameterized Constructors…

C++ allows us to initialize the various member


variables of various objects with different values.

12
DECLARING PARAMETERIZED CONSTRUCTORS …

class <class-name>
{

public:
// constructor declared.
<class-name>(arguments);

};

13
Parameterized Constructors… Example …

class circle public:


{ circle( int r )
private: {
int radius; radius = r;
float area;
};

};

14
The Object Declaration Statement…

circle c1; would not work.


We must have to pass the initial value as argument
to the constructor function when an object is
created.
This can be done in two ways.
By calling the constructor explicitly.
circle c1
= circle(10);
By calling the constructor implicitly.
circle c2(20);
15
Multiple Constructors…
Define more than one constructor function within
one class.
Known as Constructor Overloading.
Depending upon how the arguments are passed
when the object is created, one of the constructor
functions would be called.

16
Multiple Constructors… Example…

class circle
{
int radius;
public:
circle() { radius = 0 };
circle (int r) { radius = r };
circle (circle & c) { radius = c.radius };

};
17
Multiple Constructors… Example…

void main() {
//Constructor with no argument.
circle c1;
//Constructor with 1 argument.
circle c2 = circle(10);
circle c3(20); // Another way.
circle c4(c3); // Copy constructor.
};
See program constr2.cpp
18
Copy Constructor…
It is used to declare (create) and initialize an
object from another object.
e.g. Circle c4(c3);
Here c3 is object of class circle and values of all
variables would be copied to object c4.

19
Difference between Assignment Operator and
Copy Constructor…

circle c1, c2;


c1 = c2; Use of Assignment Operator.
circle c3 = c1; Use of Copy Constructor.

Assignment Operator does not create a new object,


Copy Constructor creates a new object and then
assigns the value of old object to new object.

20
Copy Constructor…
Copy constructor takes a reference to an object of
the same class as itself as an argument.
Click here: how the copy constructor is defined
When no copy constructor is defined, the
compiler supplies its own copy constructor.

See program constr3.cpp


21
Dynamic Constructors …
Used to allocate memory while creating objects.
Enable the system to allocate the right amount of
memory for each object when the objects are not
of the same size.
This results into savings of memory.
Use new operator to allocate dynamic memory.

See program constr4.cpp


22
new & delete Operators…
We can use malloc ( ) and calloc ( ) functions to
allocate memory dynamically at run time.
C++ provides new operator to carry out same
thing.
Better and easier to use new instead of using
malloc ( ) and calloc ( ).

23
new & delete Operators…
Object created by new will remain in existence
until it is destroyed by using delete.
Thus lifetime of an object is directly under our
control irrespective to the block structure of the
program.
new can be used to create objects of any type.

24
new & delete Operators…
SYNTAX:
pointer-variable = new data-type.
EXAMPLE:
int * p = new int;
float * f = new float;
*p = 30;
*f = 25.0;
will assign 30 and 25.0 to the newly created int and
float object respectively.

25
new & delete Operators…

We can initialize the memory using new operator.


Example: int * p = new int(30);
new can be used to create a memory space for any
data type including user-defined types such as
arrays, structures and classes.
Example: int * p = new int[10];

See program constr4.cpp


26
new & delete Operators…

If sufficient memory is not available for


allocation, new returns a null pointer.

27
new & delete Operators…

Memory allocated by new operator has to be


released by delete operator.
Example:
delete p , f; deletes objects p & f.
delete [10]p ; will delete dynamically
allocated array.
delete [ ]p; will delete the entire array
pointed by p.

See program constr4.cpp


28
Destructors …
Used to de-allocate memory occupied by the
objects.
It is a member function having same name as the
class name.
But is preceded by a tilde ( ~ ).
e.g. ~circle ( ) { };
It never takes any argument nor does it returns
any value.

29
Destructors …
Will be invoked implicitly by the compiler upon
exit from:
Function (if class is defined within any
function.)
Or from the program.
Whenever new is used to allocate memory in the
constructors, use delete to free that memory.

See program constr5.cpp


30
Summary …
Constructor is a special member function.
Enables an object to initialize itself when it is
created.
It has the same name as that of a class.
Generally used to initialize variables and to
allocate memory.
Constructors can be overloaded.

31
Summary …
When an object is created and initialized at the
same time, a copy constructor gets called.
Use of new and delete operator allows us to
allocate and de-allocate memory for the object
dynamically.
Destructor is used to destroy the objects when
they are no longer required.

32

You might also like