0% found this document useful (0 votes)
19 views39 pages

4 Constructor Destructor

The document discusses constructors and destructors in C++, explaining their definitions, characteristics, and types. Constructors are special member functions that create and initialize objects, while destructors clean up and recycle objects when they go out of scope. It also covers default, parameterized, and copy constructors, along with examples and rules for destructors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views39 pages

4 Constructor Destructor

The document discusses constructors and destructors in C++, explaining their definitions, characteristics, and types. Constructors are special member functions that create and initialize objects, while destructors clean up and recycle objects when they go out of scope. It also covers default, parameterized, and copy constructors, along with examples and rules for destructors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Lecture 8

CONSTRUCTORS AND DESTRUCTORS


Constructor:
A constructor is a special member function that
creates and initializes an object.

Destructor:
destructor is a special member function that cleans
and destroys an object.
Constructor:
•A constructor is a member function that creates
an object when it is called and initializes the
data members of an object when it is executed.

•The declaration of the data members in the


class definition does not initialize the data
members. the declaration just gives the names
and the types of the data members.
Two characteristics of Constructor:

•It does not have a return value, and its name is


the same as the name of the class.

•A constructor cannot have a return value (not


even void) because it is not designed to return
anything.

• The purpose of constructor is to create an


object and initializes the data member s.
How constructors are different from a
normal member function?

A constructor is different from normal functions in


following ways:

•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)
Types of constructors:

1)Default constructors

2)Parameter constructors

3)Copy constructors
1)Default constructor

Default constructor is the constructor which


doesn’t take any argument. It has no
parameters.

Note: Even if we do not define any constructor


explicitly, the compiler will automatically provide a
default constructor implicitly.
Default Constructor - example
#include <iostream>
using namespace std; int main()
{
class construct { // Default constructor called
public: automatically when the object
int a, b; is created
construct c;
// Default Constructor cout << "a: " << c.a << endl
definition << "b: " << c.b;
construct( ) return 1;
{ }
a = 10;
b = 20; Output:
} a: 10
}; b: 20
2) Parameterized Constructor:

•It is possible to pass arguments to constructors.

•These arguments help initialize an object when it is


created.

• To create a parameterized constructor, simply add


parameters to it the way you would to any other
function.

• When you define the constructor’s body, use the


parameters to initialize the object.
Parameterized Constructor
#include <iostream> int getY() - example
using namespace std; {
return y;
class Point { }
private: }; // end of class definition
int x, y;

public: int main()


// Parameterized Constructor {
Point(int x1, int y1) // Constructor called
{ Point p1(10, 15);
x = x1;
y = y1; // Access values assigned by constructor
} cout << "p1.x = " << p1.getX() << ", p1.y
= " << p1.getY();
int getX()
{ return 0;
return x; }
} Output:
p1.x = 10, p1.y = 15
Parameterized Constructor :

The Parameterized constructor can be called


explicitly or implicitly.

Point p1 = Point(10, 20); // Explicit call

Point p1(10, 20); // Implicit call


Uses of Parameterized constructor:

•It is used to initialize the various data


elements of different objects with different
values when they are created.

•It is used to overload constructors. (will be


discussed later)
3) copy constructor:

•A copy constructor is a member function


which initializes an object using another object
of the same class.

•A copy constructor has the following general


function prototype:
ClassName (const ClassName &old_obj);
copy constructor:
A copy constructor copies the data member values of
the given object to the new object just created.

After calling the copy constructor, the source and the


destination objects have exactly the same value for each
data member, although they are different objects.

The copy constructor has only one parameter that


receives the source object by reference.

The const modifier in front of the parameter type


guarantees that the pass-by-reference cannot change the
source object.
#include<iostream> {
using namespace std; Point p1(10, 15); // Normal
constructor is called here
class Point Point p2 = p1; // Copy constructor is
{ called here
private:
int x, y; cout << "p1.x = " << p1.getX() << ", p1.y
public: = " << p1.getY();
Point(int x1, int y1) cout << "\np2.x = " << p2.getX() << ",
{ p2.y = " << p2.getY();
x = x1; y = y1;
} return 0;
// Copy constructor }
Point(const Point &b)
{ Output:
x = b.x;
y = b.y; p1.x = 10, p1.y = 15
} p2.x = 10, p2.y = 15
int getX() { return x; }
int getY() { return y; }
};
When is copy constructor called?

A Copy Constructor may be called in


following cases:

1.When an object of the class is passed (to a


function) by value as an argument.

2.When an object is constructed based on


another object of the same class
Destructors:

A destructor is a special-purpose member function with no


parameter and is designed to clean up and recycle an object.

A destructor is guaranteed to be automatically called and


executed by the system when the object instantiated from
the class goes out of scope.

Example, If we have instantiated five objects from the class,


the destructor is automatically called five times to guarantee
that all objects are cleaned up
Two special characteristics of destructors:

1) First, the name of the destructor is the name


of the class preceded by a tilde symbol (~).

2) Second, like a constructor, a destructor


cannot have a return value (not even void)
because it returns nothing.
Syntax of Destructor:

~class_name ( )
{
//Some code
}

When does the destructor get called?


A destructor is automatically called when:
1) The program finished execution.
2) When a scope (the { } parenthesis) containing local
variable ends.
3) When you call the delete operator.
Destructor-Example
#include <iostream> //Member function
using namespace std; void display()
class HelloWorld {
{ cout<<"Hello World!"<<endl;
public: }
//default Constructor };
HelloWorld()
{ int main()
cout<<"Constructor is {
called"<<endl; //Object created
} HelloWorld obj;
//Destructor
~HelloWorld() //Member function called
{ obj.display();
cout<<"Destructor is return 0;
called"<<endl; }
}
OUTPUT:
Constructor is called
Hello World!
Destructor is called
Destructor rules:

1) Name should begin with tilde sign(~) and must


match class name.

2) There cannot be more than one destructor in a class.

3) Unlike constructors that can have parameters,


destructors do not allow any parameter.

4) They do not have any return type, just like


constructors.

5) When you do not specify any destructor in a class,


compiler generates a default destructor and inserts it
into your code.
Lets have a Discussion…

Are You Ready??


Q1-Predict the output??????
include "iostream" void display()
using namespace std; {
cout<<x<<" "<<y;
class point { }
private:
double x, y; };

public:
// Non-default Constructor int main(void) {
point (double px, double py) point a;
{ point b = point(5, 6);
x = px, y = py; b.display();
}
}
Q1-Predict the output??????
include "iostream" void display()
using namespace std; {
cout<<x<<" "<<y;
class point { }
private:
double x, y; };
ERROR
public: !!!
// Non-default Constructor int main(void) {
point (double px, double py) point a;
{ point b = point(5, 6);
x = px, y = py; b.display();
} a.display();

}
Why Its Error??????

Whenever we define one or more non-default


constructors( with parameters ) for a class,
a default constructor should also be explicitly
defined as the compiler will not provide a default
constructor in this case.

However, it is not necessary but it’s considered to


be the best practice to always define a default
constructor.
Q1
include "iostream"
using namespace std; void display()
{ cout<<x<<" "<<y; }
class point { };
private:
double x, y; int main(void) {
point a; // remove this
public: line
// Non-default Constructor point b = point(5, 6);
b.display();
point (double px, double py)
{
x = px, y = py; }
}
Q1-Modified code: {
include "iostream" cout<<x<<" "<<y;
using namespace std; }

class point { };
private:
double x, y; int main(void) {
point b = point(5, 6);
b.display();
public:
// Non-default Constructor }
point (double px, double py) OUTPUT:
{ 5 6
x = px, y = py;
}

void display()
Q2) Predict the Output ?
#include<iostream>
using namespace std;

class Point
{
Point( ) { cout << "Constructor called"; }
};

int main()
{
Point t1;
return 0;
}

(A) Compiler Error


(B) Runtime Error
(C) Constructor called
Answer: (A)

Complier Error:
By default all members of a class are private. Since
no access specifier is there for Point(), it becomes
private and it is called outside the class when p1 is
constructed in main.
Q3) Predict the output:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(const Point &p)
{ x = p.x; y = p.y; }
};

int main()
{
Point p1;
Point p2 = p1;
return 0;
}
OUTPUT:

Point p1; // shows COMPILER ERROR

Compiler doesn’t create a default constructor if we


write any constructor even if it is copy constructor
Q4) Predict the output:

#include <iostream>
using namespace std;

class Point
{
int x, y;
public:
Point(int i, int j) { x = i; y = j; }
int getX() { return x; }
int getY() { return y; }
};

int main()
{
Point p1(10, 20);
Point p2 = p1; // This compiles fine
cout << "x = " << p2.getX() << " y = " << p2.getY();
return 0;
}
OUTPUT:

x = 10 y = 20
Compiler creates a copy constructor if we don’t write our own.
Compiler creates it even if we have written other constructors in class.
Q5) Like constructors, can there be more
than one destructors in a class?

a) Yes
b) No
Answer:
No, there can only one destructor in a class with classname
preceded by ~, no parameters and no return type.
Q6) Predict the output??

#include<iostream.h>
class IndiaBix
{
public: IndiaBix()
a)The program will print the output India.
{
cout<< "India"; b)The program will print the output Bix.
}
c)The program will print the output IndiaBix.
~IndiaBix()
{ d)The program will report compile time erro
cout<< "Bix";
}
};
int main()
{
IndiaBix objBix;
return 0;
}
Answer:
c)The program will print the output IndiaBix.

You might also like