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

Constructor Destructor

Uploaded by

abhijeetpundir27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Constructor Destructor

Uploaded by

abhijeetpundir27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CONSTRUCTOR IN C++

It is a special method that is invoked automatically at the time an object of a class is


created. It is used to initialize the data members of new objects generally. The
constructor in C++ has the same name as the class or structure. It constructs the values
i.e. provides data for the object which is why it is known as a constructor.

SYNTAX OF CONSTRUCTORS IN C++

<class-name> (list of parameters)


{
// body_of_constructor
}

EXAMPLE 1:
string dept;
department ()
{
dept=”department name”;
}

EXAMPLE 2:
string dept;
department (string d)
{
dept=d;
}

CHARACTERISTICS OF CONSTRUCTORS IN C++


• The name of the constructor is the same as its class name.
• Constructors are mostly declared in the public section of the class though they can be
declared in the private section of the class.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
TYPES OF CONSTRUCTORS
Constructors can be classified based on in which situations they are being used. There are
3 types of constructors in c++:
1. Default constructor: no parameters. They are used to create an object with default
values.
2. Parameterized constructor: takes parameters. Used to create an object with specific
initial values.
3. Copy constructor: takes a reference to another object of the same class. Used to create
a copy of an object.

DEFAULT CONSTRUCTOR:
A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is
also called a zero-argument constructor. A constructor without any arguments or with the default
value for every argument is said to be the default constructor.

A constructor that has zero parameter list or in other sense, a constructor that accepts no
arguments is called a zero-argument constructor or default constructor.

If default constructor is not defined in the source code by the programmer, then the compiler
defines the default constructor implicitly during compilation.
If the default constructor is defined explicitly in the program by the programmer, then the
compiler will not define the constructor implicitly, but it calls the constructor implicitly.

SYNTAX OF DEFAULT CONSTRUCTOR


classname()
{
// body_of_constructor
}
or
student()
{
//body of constructor
}
EXAMPLE 1:
student()
{ int x=5;
cout<<”value of x : ”<<x<<endl;
}
EXAMPLE 2:
int x;
student()
{ x=5;
cout<<”value of x : ”<<x<<endl;
}

PROGRAM:
Constructor definition inside the class
#include <iostream>
using namespace std;
class student
{
public string dept;
public:
student()
{
dept=”department name”;
cout<<"student department : "<<dept<<endl;
}
};
int main()
{
student s1; //creating an object of employee
student s2;
return 0;
}

Constructor definition outside the class


#include <iostream>
using namespace std;
class student
{
public string dept;
public:
student();
};
student :: student()
{
dept=”department name”;
cout<<"student department : "<<dept<<endl;
}
int main()
{
student s1; //creating an object of employee
student s2;
return 0;
}

PARAMETERIZED CONSTRUCTOR:
Parameterized constructors make it possible to pass arguments to constructors.
Typically, 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.

SYNTAX OF PARAMETERIZED CONSTRUCTOR


classname (parameters...) {
// body of parameterized constructor
}

or
classname (arg1, arg2, arg3, ….., argn) {
// body of parameterized constructor
}

EXAMPLE 1:
student (string name, int age, string dept)
{
cout<<”name : “<<name<<endl;
cout<<”age : ”<<age<<endl;
cout<<”department : “<<dept<<endl;
}

EXAMPLE 2:
string name;
int age;
string dept;
student (string n, int a, string d)
{
name=n;
age=a;
dept=d;
cout<<”name : “<<name<<endl;
cout<<”age : ”<<age<<endl;
cout<<”department : “<<dept<<endl;
}

PROGRAM:
#include <iostream>
using namespace std;
class employee {
public:
int id; //data member
string name; //data member
float salary;
employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<”id : ”<<id<<”name : “<<name<<”salary : ”<<salary<<endl;
}
};
int main( ) {
employee e1 =employee(101, "sonoo", 890000);
employee e2=employee(102, "nakul", 59000);
e1.display();
e2.display();
return 0;
}
COPY CONSTRUCTOR:
A member function known as a copy constructor initializes an item using another object from
the same class-an in-depth discussion on copy constructors.
Every time we specify one or more non-default constructors (with parameters) for a class, we
also need to include a default constructor (without parameters), as the compiler won't supply
one in this circumstance. The best practice is to always declare a default constructor, even
though it is not required.
A reference to an object belonging to the same class is required by the copy constructor.

SYNTAX OF COPY CONSTRUCTOR


data type member;
classname (classname &obj)
{
member=obj.member;
// body_containing_logic
}

EXAMPLE 1:
sample(sample &t)
{
id=t.id;
}

PROGRAM:
#include <iostream>
using namespace std;
class student {
int rno;
string name;
double fee;
public:
student(int, string, double);
// copy constructor
student(student& t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
cout << "copy constructor called" << endl;
}
// function to display student details
void display();
};

// implementation of the parameterized constructor


student::student(int no, string n, double f)
{
rno = no;
name = n;
fee = f;
}

// implementation of the display function


void student::display()
{
cout << rno << "\t" << name << "\t" << fee << endl;
}

int main()
{
// create student object with parameterized constructor
student s(1001, "manjeet", 10000);
s.display();

// create another student object using the copy


// constructor
student manjeet(s); or student manjeet=s;
manjeet.display();

return 0;
}

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.

SYNTAX OF CONSTRUCTOR OVERLOADING


class classname
{
public:
data type member1;
data type member2;

// constructor with no parameters


classname()
{
//body of constructor
}

// constructor with two parameters


classname(data type member1, data type member2)
{
//body of constructor
}

void disp()
{
cout<<”output here”;
}
};

int main()
{
classname obj1;
classname obj2( val1,val2);
obj1.disp();
obj2.disp();
return 1;
}
PROGRAM:
// 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;
}
};
int main()
{
// constructor overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

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

DESTRUCTORS
Destructor is an instance member function that 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.
In this article, we will learn about the destructors in c++, how they work, how and why to create
the user defined destructors with the code examples. At the end, we will look at some
commonly used questions about c++ destructors.

SYNTAX TO DEFINE DESTRUCTOR


~ <class-name>() {
// some instructions
}
just like any other member function of the class, we can define the destructor outside the
class too:
<class-name> {
public:
~<class-name>();
}
<class-name> :: ~<class-name>() {
// some instructions
}
But we still need to at least declare the destructor inside the class.
Characteristics of a destructor
• A destructor is also a special member function like a constructor. Destructor destroys
the class objects created by the 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 created by the constructor. Hence,
destructor cannot be overloaded.
• It cannot be declared static or const.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when an object goes out of scope.
• Destructor release memory space occupied by the objects created by the constructor.
• In destructor, objects are destroyed in the reverse of an object creation.
The thing is to be noted here if the object is created by using new or the constructor uses new
to allocate memory that resides in the heap memory or the free store, the destructor should use
delete to free the memory.

Program:
// C++ program to demonstrate the execution of constructor
// and destructor

#include <iostream>
using namespace std;

class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;

return 0;
}

Output
Constructor executed
Destructor executed

Program 2:
// C++ program to demonstrate the number of times
// constructor and destructors are called

#include <iostream>
using namespace std;
// It is static so that every class object has the same
// value
static int Count = 0;
class Test {
public:
// User-Defined Constructor
Test()
{
// Number of times constructor is called
Count++;
cout << "No. of Object created: " << Count << endl;
}

// User-Defined Destructor
~Test()
{
// It will print count in decending order
cout << "No. of Object destroyed: " << Count
<< endl;
Count--;
// Number of times destructor is called
}
};

// driver code
int main()
{
Test t, t1, t2, t3;

return 0;
}

Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1

CALLING OF BASE CONSTRUCTOR IN DERIVE CLASS


public class Abc
{
public int p, q;
public Abc(int p1, int p2)
{
p = p1;
q = p2;
}
public int sum(int x, int y)
{
return (x + y);
}

//derived class/ child class


public class Pqr : Abc
{
public int a;
public Pqr(int a1,int p1, int p2):base(p1,p2)
{
a = a1;
}
public int sub(int x, int y)
{
return (x - y);
}
}

CONSTRUCTOR IN DERIVE CLASS


// C++ program to show the order of constructor call
// in single inheritance

#include <iostream>
using namespace std;

// base class
class Parent
{
public:

// base class constructor


Parent()
{
cout << "Inside base class" << endl;
}
};

// sub class
class Child : public Parent
{
public:

//sub class constructor


Child()
{
cout << "Inside sub class" << endl;
}
};

// main function
int main() {

// creating object of sub class


Child obj;

return 0;
}

INITIALIZE VALUES FOR DERIVE CLASS


#include <iostream>
using namespace std;

// base class
class Parent {
int x;

public:
// base class's parameterized constructor
Parent(int i)
{
x = i;
cout << "Inside base class's parameterized "
"constructor"
<< endl;
}
};

// sub class
class Child : public Parent {
public:
// sub class's parameterized constructor
int z;
Child(int x): Parent(x),z(x+10)
{
cout << "Inside sub class's parameterized "
"constructor"
<< z<<endl;
}
};

// main function
int main()
{

// creating object of class Child


Child obj1(10);
return 0;
}

You might also like