Constructor and Destructor, Constructor Overloading, C++ Tutorials

Constructor& Destructor

 1. Introduction

In C++ we are able to create user-defined data types such as class that behave very similar to built-in data types. That means we can initialize a class type variable(object) when it is declared.

C++ provides a mechanism called constructor to achieve this. That means a constructor initializes an object and a destructor destroys the object.

Let us understand the concept in detail.

2. Constructor

A constructor is a special member function whose name is same as the class name. It is invoked automatically when the object of the class is created. It is named so because it constructs the values of data members of the class.

Let us execute (Run this program) the following program to understand the work of a constructor.

#include<iostream.h>

class demo

{

        public:

                demo()

                {

                        cout<<"Welcome to Constructor"<<endl;

                }

};

void main()

{

        demo d1,d2,d3,d4,d5;

 

Output

Welcome to Constructor

Welcome to Constructor

Welcome to Constructor

Welcome to Constructor

Welcome to Constructor

Note that in the above program the member function demo( ) is a constructor whose   name is same as the class name. The constructor contains a single statement and is invoked 5 times as 5 objects (d1,d2,d3,d4 and d5)have been declared in the main( ) function. Mark that the constructor demo( ) is invoked automatically when an object of the class is created. It does not require dot membership operator to invoke itself.

 3. Characteristics of Constructor

  • Its name is same as the class name.
  • It is always declared in the public category of the class.
  • It doesn't have any return type, not even void.
  • The number of objects created, the number of times the constructor will be invoked.(As seen in previous example)
  • It can have default arguments.
  • It is also used to initialize private data members of a class.
  • It cannot be made as virtual.(The meaning of virtual is explained in chapter-7)
  • There can be more than one constructor in a program, but with different signatures.

 Types of Constructor

The constructor in C++ is mainly classified as:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

1. Default Constructor

The constructor which does not take any argument is known as default constructor. A default constructor can be defined in two ways:

i) Inside the class definition

ii) Outside the class definition

i)   Inside the class definition

The general form of defining a default constructor holds the following syntax.

class classname

{

        private:

                //Data members

        public:

                classname()

                {

                        //Default Constructor Statements

                }

};

 

 

ii)  Outside the class definition

The general form of defining a default constructor outside the class holds the following syntax.

class classname

{

        private:

                //Data members

        public:

                classname(); // Default Constructor prototype

};

 

Outside the class

 

classname::classname()

{

        //Default Constructor Statements

}

Remember

When the default constructor is defined outside the class, its prototype must be declared in the public category of the class.

Program 1

Write a program to illustrate the use of default constructor.

#include<iostream.h>

#include<constream.h>

class demo

{

        private:

                int a;

                float b;

        public:

                demo();

};

demo::demo()

{

        cout<<"Enter the value of a and b :";

        cin>>a>>b;

        cout<<"a = "<<a<<endl;

        cout<<"b = "<<b<<endl;

}

void main()

{

        demo d1;

}

 

Output

Enter the value of a and b :

21

5.9

a = 21

b = 5.9

Explanation

In the above program, the object d1 is initialized with a=21 and b=5.9 by the default constructor demo( ). The default constructor demo() is defined outside the class. It is invoked only once because there is only one object d1 declared in the function main( ).

Remember

If no constructor is defined in the class, then the compiler provides its own default constructor called as implicit constructor to facilitate object creation. 

2. Parameterized Constructor

The constructor which takes argument is known as parameterized constructor. A parameterized constructor can be defined in two ways:

i) Inside the class definition

ii) Outside the class definition

i)  Inside the class definition

The general form of defining a default constructor holds the following syntax.

class classname

{

        private:

                //Data members

        public:

                classname(datatype arg1, datatype arg2,......)

                {

                        //Default Constructor Statements

                }

};

 

 

ii)          Outside the class definition

The general form of defining a parameterized constructor outside the class holds the following syntax.

 

class classname

{

        private:

                //Data members

        public:

                classname(datatype,datatype,...); // Parameterized Constructor                       prototype

};

Outside the class

 

classname::classname(datatype arg1, datatype arg2,......)

{

        // Parameterized  Constructor Statements

}

Remember

When the default constructor is defined outside the class, its prototype must be declared in the public category of the class.

2.2.1. Invoking a parameterized constructor

We must pass the initial values as arguments to parameterized constructor when during object declaration.

Method1(Explicit call)

class_name object_name=class_name(value1, value2,....);

Example

          demo d1=demo(21,5.9);

Method2(Implicit call)

class_name object_name(value1, value2,....);

Example

          demo d1(21,5.9);

Among these two methods, the second method is shorthand and easy to use.

Program 2

Write a program to illustrate the use of parameterized constructor.

#include<iostream.h>

class demo

{

        private:

                int a;

                float b;

        public:

                demo(int,float);

};

demo::demo(int x, float y)

{

        a=x;

        b=y;

        cout<<"a = "<<a<<endl;

        cout<<"b = "<<b<<endl;

}

void main()

{

        demo d1(22,6.9);

 

}

 

Output

a = 22

b = 6.9

Explanation

In the above program, the object d1 is initialized with two values 22 and 6.9, which are passed to the formal arguments x and y in the parameterized constructor demo(int x, float y ). The parameterized constructor demo(int x, float y) is defined outside the class. Further the values of x and y are assigned to the data members a and b respectively and yield the output as above.

************************************************

Destructor

A destructor is also a special member which is invoked automatically when an object is destroyed. It complements the operation performed by any of the constructor. The destructor is declared with a tilde (~) character followed by its class name.

The destructor can be defined in two ways:

i) Inside the class definition

ii) Outside the class definition

i)  Inside the class definition

The general form of defining a destructor holds the following syntax.

class classname

{

        private:

                //Data members

        public:

                ~classname()

                {

                        //Destructor Statements

                }

};

ii)  Outside the class definition

The general form of defining a destructor outside the class holds the following syntax.

class classname

{

        private:

                //Data members

        public:

                ~classname(); // Destructor prototype

};

classname::~classname( )  ß---------- Outside the class

{

        // Copy  Constructor Statements

}

Remember

When the destructor is defined outside the class, its prototype must be declared in the public category of the class. The destructor does not take any argument.

Program 4.5

Write a program to illustrate the use of destructor.

#include<iostream.h>

#include<constream.h>

int obj_count=0;

class example

{

        public:

                example()

                {

                        ++obj_count;

                        cout<<"Total objects created :"<<obj_count<<endl;

                }

                ~example()

                {

                        cout<<"Total objects destroyed :"<<obj_count<<endl;

                        --obj_count;

                }

};

main()

{

        clrscr();

        example e1,e2,e3;

        return(0);

}

 

Output

Total objects created :1

Total objects created :2

Total objects created :3

Total objects destroyed :3

Total objects destroyed :2

Total objects destroyed :1

Explanation

In the above program the objects e1,e2 and e3 are created and destroyed which is illustrated with a variable obj_count(initially set to zero). Note that objects are destroyed in the reverse order of creation.

4.6. Working of Constructor with Local  and Global object

The constructor always invoked first for a global object on priority, and then it searches for the local object inside the functions.

Example

#include<iostream.h>

class demo

{

        public:

                demo()

                {

                        cout<<"Welcome to Constructor"<<endl;

                }

};

demo g1;

void main()

{

        cout<<"We are in main"<<endl;

demo l1;

 

Output

Welcome to Constructor (for global object g1)

We are in main

Welcome to Constructor(for local object l1)

Explanation

In the above program, the constructor demo() is invoked for the global object g1 first, then it enters into the main() function and invoked the constructor demo() for the local object  l1.

Constructor Overloading

Constructor overloading is an important feature of the constructors that a class can have multiple constructors having same name but with different signature with respect to number and type of arguments being provided.

Example

#include<iostream.h>

#include<constream.h>

class account

{

        private:

                int acc_no;

                float balance;

        public:

                account();

                account(float);

                account(int,float);

                void display();

};

account::account()

{

        cout<<"Enter a/c no and balance of the 1st customer :";

        cin>>acc_no>>balance;

}

account::account(float b)

{

        cout<<"Enter a/c no of the 2nd customer :";

        cin>>acc_no;

        balance=b;

}

account::account(int a, float b)

{

        acc_no=a;

        balance=b;

}

void account::display()

{

        cout<<acc_no<<"\t"<<balance<<endl;

}

main()

{

        clrscr();

        account a1;

        account a2(6500.00);

        account a3(12347,8040.00);

        cout<<"\t"<<" A/C No"<<"\t\t"<<"Balance "<<endl;

        cout<<"Customer1 :";a1.display();

        cout<<"Customer2 :";a2.display();

        cout<<"Customer3 :";a3.display();

        return(0);

}

 

Output

Enter a/c no and balance of the 1st customer :

12345

4500.75

Enter a/c no of the 2nd customer :12346

 

        A/C No     Balance

Customer1 :12345        4500.75

Customer2 :12346        6500

Customer3 :12347        8040

Explanation

The above program uses 3 constructors 3 times with different argument types and yields details of 3 customers for 3 objects a1, a2 and a3.

SUMMARY

1.Constructors and destructor decide how the objects of a class created, initialize, copied and destroyed.

2.They have the same name as the class name.

3. It is possible to define constructor with arguments like normal function.

4. When the constructor and destructor are private, they cannot be executed implicitly. They must be executed explicitly.

How we help you? - C++ Assignment Help 24x7

We offer C++ assignment help, C++ assignment writing help, programming assessments writing service, C++ tutors support, step by step solutions to Polymorphism problems, Constructor and Destructor programming answers, C++ assignment experts help online. Our assignment help service is most popular and browsed all over the world for each grade level.

Why choose us - The first thing come in your mind that why choose us why not others what is special and different about us in comparison to other site. As we told you our team of expert, they are best in their field and we are always live to help you in your assignment which makes it special.

Key features of services are listed below:

  • Confidentiality of student private information
  • 100% unique and original solutions
  • Step by step explanations of problems
  • Minimum 4 minutes turnaround time - fast and reliable service
  • Secure payment options
  • On time delivery
  • Unlimited clarification till you are done
  • Guaranteed satisfaction
  • Affordable price to cover maximum number of students in service
  • Easy and powerful interface to track your order

assignment help

Popular Writing Services:-

  • Immunology get immunology assignment help online, immunology assignment writing service, immunology papers, essay, thesis and dissertation from biology assignment experts.
  • C Tutorial C Assignment Help, C Programming Help, C Programmer service, tutor service, c project help, C programming solutions
  • Physiology get physiology assignment help online, physiology writing service, paper writing help, thesis and dissertation help from physiology assignment experts/writers.
  • Pearson Lab and Homework pearson homework help and lab assignments: we do your pearson lab homework or assignments in nominal prices, get pearson lab solved online from online tutors
  • Electrochemistry Finding expert in electrochemistry who may solve your electrochemistry assignment or homework? Get electrochemistry assignment help and assessments writing help
  • Classification and Division Essay Looking for reliable essay writing service? Seeking help in writing Writing a division and classification essay? Live essay writers support to write essay.
  • Materials science Get Materials science Assignment Help Online, assessment help and Writing Service from Physical chemistry Assignment Experts.
  • Law and Ethics Hire Law tutors for Business Law and Ethics Assignment Help & legal and law homework help, legal case assignment writing service in lowest price.
Captcha

Get Academic Excellence with Best Skilled Tutor! Order Assignment Now! Submit Assignment