Constructor

A constructor is a special method which is automatically called whenever an instance of class is created. It is used to initialize objects of a class. A constructor is also used to run a default code when an object is created.

Properties of Constructor:

  • Its name is same as the name of class.
  • It has no return type.
  • It is called whenever the object is created. (default constructor).
  • It is used to initialize the data members of class
  • Constructor is always public.
So, properties and behaviors are members of class and declared inside the class.

Understanding Constructors using real life example:

Suppose you went to a shop to buy a pen. You say to the shop keeper, give me a marker. You are not specifying the brand or ink color. He will give you the most hot marker selling in the market. This is the default constructor. If you say give me a marker of xyz brand and ink should be blue, this is parameterized constructor. And if you take a marker with you and show it to the shopkeeper and say that give me a marker like this. This is your copy constructor. Let us explore some more details.

constructor.cpp
#include <iostream>
using namespace std;

class Students{
	//public access specifier
	public:
		//constructor
		Students(){
			cout<<"Constructor called"<<endl;
		}
};
int main(){
	cout<<"Line before creating object."<<endl;
	Students std1;
	cout<<"Constructor called."<<endl;
}

Default Constructors:

They take no parameter. Now we will see, how a constructor can initialize the data members.

constructor.cpp
#include <iostream>
using namespace std;

class Students{
	//public access specifier
	public:
		//data members
		int marks;
		int rollNo;

		Students(){
			marks = 0;
			rollNo = 0;
		}
};
int main(){
	Students std1;
  std1.marks = 100;
  std1.rollNo = 1234;
	cout<<"Marks = "<<std1.marks<<endl;
	cout<<"Roll no = "<<std1.rollNo<<endl;
}

Parameterized Constructor:

A constructor that takes one or more parameter to set values of data members.
These values are passed when object is created. It is just like when we create and call functions.

constructor.cpp
#include <iostream>
using namespace std;

class Students{
	//public access specifier
	public:
		//data members
		int marks;
		int rollNo;
		//parameterized constructor
		Students(int marks, int rollNo){
			this->marks = marks;
			this->rollNo = rollNo;
		}
};
int main(){
	Students std1(100, 1234);
	cout<<"Marks = "<<std1.marks<<endl;
	cout<<"Roll no = "<<std1.rollNo<<endl;
}

If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body)


"this" keyword:
this refers to the member of current class in which we are present.
// Inside the class definition
class MyClass {
public:
    int marks;

    // Constructor with member initializer list
    MyClass(int marks) : marks(marks) {}
};

// Example usage
MyClass obj(85);

Note:
It is not necessary to set the same names of parameters of constructor and data members.
Use of this is also optional.


constructor.cpp
#include <iostream>
using namespace std;

class Students{
	//public access specifier
	public:
		//data members
		int marks;
		int rollNo;
		//parameterized constructor
		Students(int marksOfstd, int rollNoOfStd){
			marks = marksOfstd;
			rollNo = rollNoOfStd;
		}
};
int main(){
	Students std1(100, 1234);
	cout<<"Marks = "<<std1.marks<<endl;
	cout<<"Roll no = "<<std1.rollNo<<endl;
}

Copy Constructor:

The copy constructor creates a new object by copying the values from existing object of class to other object of the same class.Copy constructor takes a reference to an object of the same class as an argument. Simply, copy constructor copies values from one object to another object.

constructor.cpp
#include <iostream>
using namespace std;
// declare a class
class square {
	private:
	 double length;
	 double height;
	public:
	 square(double len, double hgt) {
	 length = len;
	 height = hgt;
	 }
	// copies data of the obj parameter
	square(square &obj) {
	 length = obj.length;
	 height = obj.height;
	 }
	 double calcArea() {
	 return length * height;
	 }
};
int main() {
	// create an object of square class
	square square1(10.5, 8.6);
	// copy contents of square1 to square2
	square square2 = square1;
	// print areas of square1 and square2
	cout << "Square 1: " << square1.calcArea();
	cout << "Square 2: " << square2.calcArea();
	return 0;
}

Constructor Overloading:

Constructor overloading is similar to function overloading.
In constructor overloading, we make two constructors. Both have
  • different numbers of parameters, Or
  • data types of parameters is different, Or
  • sequence of parameters is different, Or
  • All three

constructor.cpp
#include <iostream>
using namespace std;

class Student {
public:
    int marks, rollNo;
	
	//default constructor
	Student(){
		marks = 0;
	}
	Student(int marks){
		this->marks = marks;
	}
	Student(int marks, int rollNo){
		this->marks = marks;
		this->rollNo = rollNo;
	}
	
};

int main() {
  Student std1;
  Student std2(10);
	Student std3(20, 123);
  cout<<"Marks of Students:"<<endl;
	cout<<"Student 1 = "<<std1.marks<<endl;
	cout<<"Student 2 = "<<std2.marks<<endl;
	cout<<"Student 3 = "<<std3.marks<<endl;
  cout<<"Roll no of Students:"<<endl;
	cout<<"Student 3 = "<<std3.rollNo<<endl;
  return 0;
}

Destructors:

Destructors are called whenever object is destroyed. It is used to deallocate memory.
It is automatically called at the end of program.

Properties of Destructors:

  • Destructor is the last function which is invoked when the object is destroyed.
  • Its name is the name of the class.
  • It is always public.
  • It can not be static or constant.
  • It is always unparameterized.
  • It has no return type even void.
  • We can not access the address of destructor.

constructor.cpp
#include <iostream>
using namespace std;

class Student {
public:
    int marks, rollNo;
	
	//constructor
	Student(){
		cout<<"Constructor called."<<endl;
	}
	//destructor
	~Student(){
		cout<<"destructor called."<<endl;
	}
	
};

int main() {
    Student std;
    cout<<"Hi there!"<<endl;
    return 0;
}