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

Constructor & Destructor

Uploaded by

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

Constructor & Destructor

Uploaded by

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

1

Class XII (Computer Science & Application)

Chapter 5 (Constructor and Destructor)

Constructor

Constructor is a special method that is invoked automatically at the time of object


creation. It is used to initialize the data members of new objects generally. The constructor has
the same name as the class or structure. Constructor is invoked at the time of object creation.

To create a constructor, we must use the same name as the class, followed by
parentheses ():

Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the
constructor)
return 0;
}

Need of Constructor

he main purpose of the constructor in C++ programming is to construct an object of


the class. In other word, it is used to initialize all class data members.

For example, in below class, constructor Car () is initializing data members with
default values. And, when we create the object of a class, this constructor will
always be called.

class Car

int id;

string model;

public:

//Constructor initializes data members


2

Car(){

this->id = 11;

this->model = "Maruti";

void display()

cout<< "Car Info:"<<" "<id<<" "<model.c_str()<<"\n";

};

int main(){

Car c;

c.display();

return 0;

Default Constructor

A constructor without any arguments or with the default value for every argument is said to
be the Default constructor.
What is the significance of the default constructor?
They are used to create objects, which do not have any specific initial value.
Is a default constructor automatically provided?
If no constructors are explicitly declared in the class, a default constructor is provided automatically
by the compiler.
Can a default constructor contain a default argument?
Yes, a constructor can contain default argument with default values for an object.
Will there be any code inserted by the compiler to the user implemented default constructor behind
the scenes?
The compiler will implicitly declare the default constructor if not provided by the programmer, will
define it when in need. The compiler-defined default constructor is required to do
certain initialization of class internals. It will not touch the data members or plain old data types
(aggregates like an array, structures, etc…). However, the compiler generates code for the default
constructor based on the situation.
3

Consider a class derived from another class with the default constructor, or a class containing another
class object with the default constructor. The compiler needs to insert code to call the default
constructors of the base class/embedded object.
// CPP program to demonstrate Default constructors
#include <iostream>
using namespace std;

class Base {
public:
// compiler "declares" constructor
};

class A {
public:
// User defined constructor
A() { cout << "A Constructor" << endl; }

// uninitialized
int size;
};

class B : public A {
// compiler defines default constructor of B, and
// inserts stub to call A constructor

// compiler won't initialize any data of A


};

class C : public A {
public:
C()
{
// User defined default constructor of C
// Compiler inserts stub to call A's constructor
cout << "C Constructor" << endl;

// compiler won't initialize any data of A


}
};

class D {
public:
D()
{
// User defined default constructor of D
// a - constructor to be called, compiler inserts
// stub to call A constructor
cout << "D Constructor" << endl;

// compiler won't initialize any data of 'a'


4

private:
A a;
};

// Driver Code
int main()
{
Base base;

B b;
C c;
D d;

return 0;
}
Output
A Constructor
A Constructor
C Constructor
A Constructor
D Constructor

Parameterized Constructors

 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 constructor in a class?
Yes, It is called Constructor Overloading.

Invocation of Constructors

Check your text book

Copy Constructor

A copy constructor is a member function that initializes an object using another object of the same
class. In simple terms, a constructor which creates an object by initializing it with an object of the
same class, which has been created previously is known as a copy constructor.

Characteristics of Copy Constructor


5

1. The copy constructor is used to initialize the members of a newly created object by copying the
members of an already existing object.
2. Copy constructor takes a reference to an object of the same class as an argument.

Sample(Sample &t)
{
id=t.id;
}
3. The process of initializing members of an object through a copy constructor is known as copy
initialization.
4. It is also called member-wise initialization because the copy constructor initializes one object with
the existing object, both belonging to the same class on a member-by-member copy basis.
5. The copy constructor can be defined explicitly by the programmer. If the programmer does not
define the copy constructor, the compile

// C++ program to demonstrate the working


// of a COPY CONSTRUCTOR
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}

// Copy constructor
Point(const Point& p1)
{
x = p1.x;
y = p1.y;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
6

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX()
<< ", p2.y = " << p2.getY();
return 0;
}

When a copy constructor called

The Copy constructor is called mainly when a new object is created from an existing object, as a copy
of the existing object.
In C++, a Copy Constructor may be called for the following cases:
1) When an object of the class is returned by value.
2) When an object of the class is passed (to a function) by value as an argument.
3) When an object is constructed based on another object of the same class.
4) When the compiler generates a temporary object.

/ CPP Program to demonstrate the use of copy constructor


#include <iostream>
#include <stdio.h>
using namespace std;

class storeVal {
public:
// Constructor
storeVal() {}
// Copy Constructor
storeVal(const storeVal& s)
{
cout << "Copy constructor has been called " << endl;
}
};

// Driver code
int main()
{
storeVal obj1;
storeVal obj2 = obj1;
getchar();
return 0;
}

Output
Copy constructor has been called
7

Dynamic Initialization of Objects


 Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value
of an object is provided during run time.
 It can be achieved by using constructors and by passing parameters to the constructors.
 This comes in really handy when there are multiple constructors of the same class with different
inputs.

Constructor Overloading

In C++, We can have more than one constructor in a class with same name, as long as each has a
different list of arguments. This concept is known as Constructor Overloading and is quite similar
to function overloading.

 Overloaded constructors essentially have the same name (exact name of the class) and different
by number and type of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which constructor
needs to be called.

// C++ program to illustrate


// Constructor overloading
#include <iostream>
using namespace std;

class construct
{

public:
float area;

// Constructor with no parameters


construct()
{
area = 0;
}

// Constructor with two parameters


construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};
8

int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

o.disp();
o2.disp();
return 1;
}

Output:
0
200

Destructors
Destructor is an instance member function which is invoked automatically whenever an object is going
to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is
destroyed.
 Destructor is also a special member function like constructor. Destructor destroys the class
objects created by constructor.
 Destructor has the same name as their class name preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object create by constructor. Hence destructor can-
not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when object goes out of scope.
 Destructor release memory space occupied by the objects created by constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

/ Example:

#include<iostream>
using namespace std;

class Test
{
public:
Test()
{
cout<<"\n Constructor executed";
}
9

~Test()
{
cout<<"\n Destructor executed";
}
};
main()
{
Test t;

return 0;
}

Output
Constructor executed
Destructor executed

Need of Destructor

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class
members when the object is destroyed. A destructor is called for a class object when that object passes
out of scope or is explicitly deleted. A destructor takes no arguments and has no return type. Its address
cannot be taken. Destructors cannot be declared const, volatile, const volatile or static. A destructor can
be declared virtual or pure virtual.

If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a
destructor. This implicitly declared destructor is an inline public member of its class.

The compiler will implicitly define an implicitly declared destructor when the compiler uses the
destructor to destroy an object of the destructor's class type. Suppose a class A has an implicitly
declared destructor.

Characteristics of Destructor

Check Textbook

You might also like