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

06.Chapter-1 Constructor

The document provides an overview of constructors and destructors in object-oriented programming, detailing their definitions, characteristics, types, and examples. It explains the differences between constructors and normal functions, introduces default, parameterized, and copy constructors, and discusses the role of destructors in memory management. Additionally, it highlights the importance of user-defined destructors when dealing with dynamically allocated memory to prevent memory leaks.

Uploaded by

Maniya Daxit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

06.Chapter-1 Constructor

The document provides an overview of constructors and destructors in object-oriented programming, detailing their definitions, characteristics, types, and examples. It explains the differences between constructors and normal functions, introduces default, parameterized, and copy constructors, and discusses the role of destructors in memory management. Additionally, it highlights the importance of user-defined destructors when dealing with dynamically allocated memory to prevent memory leaks.

Uploaded by

Maniya Daxit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

305 – object Oriented Programming

Constructor and Destructor

Educator:
Asst. Prof. Ms. Twinkle S. Panchal
Sutex Bank College of Computer Applications and Science, Amroli
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 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 value of data members of the
class.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
A constructor is declared and defined as
follows:
¬ // Class with Constructor
Class data
{
int m,n;
Public:
data() // Constructor Declared or [ data(void) ]
{
m=0; n=0;
}
}; 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
Constructor’s Characteristics:
¬ Constructor should be declared in the public section.
¬ Constructor are invoked automatically when the objects are created.
¬ Constructor do not have return types, not even void and therefore, and they cannot
return values.
¬ Constructor cannot be inherited but derived class can call the base class.
¬ Like other C++ functions, they can have default arguments
¬ Constructors make implicit call to the “new” and “delete” operators when a memory
allocation is required.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
How Constructor is different from normal
function ?
¬ Constructor has same name as the class itself
¬ Constructors don’t have return type
¬ A constructor is automatically called when an object is created.
¬ If we do not specify a constructor, C++ compiler generates a default constructor for
us (expects no parameters and has an empty body).

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Types of Constructor
¬ There are 3 Types of Constructor:
¬ 1) Default Constructor
¬ 2) Parameterized Constructor
¬ 3) Copy Constructor

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
1) Default Constructor
class data{
¬ Default constructor is the public:
int a, b;
constructor which doesn’t take any
argument. data() // Default Constructor
{
¬ It has no parameters. cout<<”Initalizing Object”
a = 10;
b = 20;
cout<<“A = ”<<a<<endl<<“B = ”<<b;
}
Default constructor };
called automatically int main()
when the object is {
created data obj;

return 0;
} 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
2) Parameterized Constructor
¬ Default Constructor initialize the data members of the class with the default values.
¬ It is also possible in the constructor to initialize the data members of the class with
different values.
¬ C++ permits us to achieve this objective by passing arguments to the constructor
function when an object is created.
¬ Those constructors that can take arguments are called parameterized constructor.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Example of Parameterized Constructor
class Point { int main()
public: {
// Constructor called
int x, y; Point p1(10, 15);
// Parameterized Constructor
Point(int x1, int y1) // Access values assigned by constructor
cout << "p1.x = " << p1.x
{ << ", p1.y = " << p1.y;
x = x1;
y = y1; return 0;
}
}
};
305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
Uses of Parameterized constructor:
¬ 1) It is used to initialize the various data elements of different objects with different
values when they are created.
¬ 2) It is used to overload constructors.

¬ Can we have more than one constructors in a class?


Yes, It is called Constructor Overloading.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Example of Constructor Overloading
Class data
{ Cons
tructo
Public: same rO
name verloadin
multi of g mea
int m,n; ple fo construct ns
r ms ( or wi
data() // Default Constructor argum in ter ms th
ents) of
{
m=0; n=0;
}
data(int i, int j) // Parameterized Constructor
{
m=i; n=j ;
}
}; 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
3) Copy Constructor
¬ A copy constructor is a member function which initializes an object using another
object of the same class.
¬ A Copy Constructor takes a reference to an object of the same class as itself as an
argument.
¬ We cannot pass the argument by value to the copy constructor
¬ Syntax:
The co
p
¬ data(data &d) { …..} C++ i y constructo
s r
of one used to copy in
object d
to ano ata
ther.
¬ Calling:
¬ data d1 = d2;
305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
Example for Copy Constructor
class Wall // copy constructor with a Wall object as
{ parameter
private: Wall(Wall &obj)
double length, height; { // initialize private variables
public: length = obj.length;
height = obj.height;
// parameterized constructor }
Wall(double len, double hgt) double calculateArea()
{ // initialize private variables {
return length * breadth;
length = len;
}
height = hgt; }; 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
}
Continue..
int main()
{
// create an object of Wall class

Wall wall1(10.5, 8.6);


// print area of wall1

cout << "Area of Room 1: " << wall1.calculateArea() << endl;


// copy contents of room1 to another object room2

Wall wall2 = wall1; // copy constructor called ..


// print area of wall2

cout << "Area of Room 2: " << wall2.calculateArea() << endl;


return 0; 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
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, thus resulting in the saving of memory.
¬ Allocate of memory to objects at the time of their construction is known as dynamic
constructors of objects.
¬ The memory is allocated with the help of new operator.

305- Object Oriented Programming Educator: Ms. Twinkle S. Panchal


Example Dynamic Constructor
Class string string(char *s)
{ {
char *name; length=strlen(s);
int length; name = new char[length + 1];
Public: strcpy(name,s);
string() }
{ };
length=0; Note: +1 is for \0 last character of string
name = new char[length + 1];
} 305- Object Oriented Programming Educator: Ms. Twinkle S. Panchal
¬ Void display()
¬{
¬ Cout<<name<<endl;
¬ } };
¬ Int main()
¬{
¬ Char *first = “joseph”
¬ String s1(first);
¬ S1.display();
¬}
305- Object Oriented Programming Educator: Ms. Twinkle S. Panchal
Destructors
¬ A destructor as its name suggests destructs or destroys the objects that are created by
a constructor.
¬ Like constructor, destructor is the member function whose name is the same as the
class name, but it is preceded by a tilde ”~”.
¬ For example : (destructor for data class is as follows)
¬ ~data()
¬{
¬ ……
¬}

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Destructor’s Importance
¬ Destructor never takes any arguments and nor does it return any value.
¬ It will be invoked by the compiler when program or any block or function finishes its
execution to clean up storage that are no longer accessible.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
How destructors are different from a
normal member function?
¬ Destructors have same name as the class preceded by a tilde (~)
¬ Destructors don’t take any argument and don’t return anything

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Can there be more than one destructor in a
class?
¬ No, there can only one destructor in a class with classname preceded by ~, no
parameters and no return type.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
When do we need to write a user-defined
destructor?
¬ If we do not write our own destructor in class, compiler creates a default destructor
for us.
¬ The default destructor works fine unless we have dynamically allocated memory or
pointer in class.
¬ When a class contains a pointer to memory allocated in class, we should write a
destructor to release memory before the class instance is destroyed.
¬ This must be done to avoid memory leak.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Example for destructor
void display()
class Demo
{ cout<<"num1 = "<< num1 <<endl;
{ cout<<"num2 = "<< num2 <<endl;
private: }
int num1, num2; ~Demo()
{
public: cout<<"Destructor Called";
Demo(int n1, int n2) } };
{
int main()
cout<<” Constructor Called"<<endl; {
num1 = n1; Demo obj1(10, 20);
num2 = n2; } obj1.display();
return 0; } 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
Example for Destructor
Int count = 0;
int main()
Class test
{
{
Public: test t1,t2;
test()
{ Return 0;
count++; }
cout<<“Created Object number ”<<count;
}
~test()
{
Cout<<“Called Destructor for Object Number ”<<count;
Count--;
} 305- Object Oriented Programming
Educator: Ms. Twinkle S. Panchal
};
Important Note:
¬ Note that the objects are destroyed in the reverse order they are created by the
constructor.

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal
Thank You

305- Object Oriented Programming


Educator: Ms. Twinkle S. Panchal

You might also like