Table of Contents
Back Button
Back to Chapter
C++ Setting Up
C++ Introduction
No items found.
C++ Basics
No items found.
C++ Control Statements
No items found.
C++ Logical Operators
No items found.
C++ Procedural Programming
No items found.
C++ Structural Programming
No items found.
C++ Implementation of OOPS
No items found.
C++ Arrays and Vectors
No items found.
C++ Error Handling
No items found.
C++ File Handling
No items found.

C++ Constructors and destructors

Constructors

Constructors are special member functions that are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and maybe defined inside or outside the class definition. It is not necessary to define a constructor, a constructor is automatically called every time an object is created.

There some features which distinguish between a constructor and a normal member function these are

  • Constructor has same name as the class itself
  • Constructors do not have any return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor while defining a class, the C++ compiler generates a default constructor for us without any parameters and an empty body.

There are 3 types of constructors, default, parameterized and copy constructors.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d7906d01-2fd4-4524-b9e7-07726a99a381/Untitled_Diagram_(24).png

Let us try to understand constructors by taking real-life examples to understand them better. Suppose you went to a shop to buy a football. When you want to buy a football, what are the options you have?

The first one: you go to a shop and say give me a football. So just saying give me a football means that you did not set which brand name and which color, you didn’t mention anything all you said is you want a football. So when we said just I want a football then whatever football is in his shop he will simply hand over that. And this is what a default constructor is!

The second option: you go to a shop and say I want a football red in color and XYZ brand. So you are mentioning this and he will give you that football. So in this case you have given the parameters. And this is what a parameterized constructor is!

Then the third one: you go to a shop and show him a sample football and ask him to give you the same football in this case you are showing him a copy of the football, so here your parameter is itself a marker of the type you want this is what copy constructor is.

Default constructor

The default constructor doesn’t take any argument. It has no parameters. In case we do not write a constructor, a default constructor is automatically generated by the compiler when an object is created.

Syntax:

className()// no return type { ..... }

Program to illustrate default constructor.

#include using namespace std; class constructorex { public: int a, b; // Default Constructor constructorex() { a = 15; b = 23; } }; int main() { // Default constructor called automatically // when the object is created constructorex c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; }
Output: a: 15 b: 23

Parameterized Constructors

It's possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor just add parameters to the default constructor the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object. Constructors are similar to functions but without return type and have the same name as the class.

#include using namespace std; class dot { private: int x, y; public: // Parameterized Constructor dot(int x1, int y1) { x = x1; y = y1; } int getX() { return x; } int getY() { return y; } }; int main() { // Constructor called dot p1(21, 20); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; }
Output: p1.x = 21, p1.y = 20

When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.

point p1=point(10,20);//Explicit call to constructor point p1(10,20);//implicit call to constructor

Uses of Parameterized constructor:

       1.It is used to initialize the various data members of different objects with different values when they are created.

      2.It is used to overload constructors.

Constructor Overloading

C++ allows us to 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.

  • Overloaded constructors essentially have the name of the class and a different number of arguments or the type of arguments basically the signature of the constructor.
  • A constructor is called depending upon the number and type of arguments passed.
  • While creating an object, arguments must be passed to let the compiler know, which constructor needs to be called.

Consider this example to demonstrate the use of Constructor overloading.

#include using namespace std; class constr { private int area; public: // Constructor with no arguments constr() { area = 0; } // Constructor with two arguments constr(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; } }; int main() { // Constructor Overloading // with two different constructors // of class name constr o=constr(15,40); constr o2( 10, 20); o.disp(); o2.disp(); return 1; }
Output: 600 200

Copy Constructor

A copy constructor is a member function that initializes an object using another object of the same class.

Whenever we define one or more non-default constructors( with arguments ) for a class, a default constructor( without arguments ) 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.

#include 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 // 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; }
Output: p1.x = 10, p1.y = 15 p2.x = 10, p2.y = 15

Destructors

A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors delete the object.

Syntax:

~className() { //Some code }

In destructors class name is preceded by " ~" this indicates the member function is a destructor.

The destructor is usually called when:-

  1. The program finished execution.
  2. When a scope containing local variable ends.
  3. When you call the delete operator.
#include using namespace std; class Hello{ public: //Constructor Hello(){ cout<<"Constructor is called"<
Output: Constructor is called Hi How are You Destructor is called

Dectructor rules

  1. Name should begin after tilde(~) sign and be the same as the class name.
  2. There cannot be more than one destructor in a class.
  3. Destructors do not allow any parameter
  4. The do not have any return type.
  5. When you do not specify a destructor in a class, the compiler generates a default destructor and inserts into your code

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?