C++ - Constructors
A constructor is a special member function of a class which automatically executed when a new object of the class is created. It allows the class to initialize member variables and allocate memory.
The constructor function is declared just like a regular member function except the class name and function name should be same without any return type.
When a constructor is not specified in a class, compiler generates a default constructor and inserts it into the code. However, it does not initialize member variables.
Syntax
//Defining constructor inside the class className(parameters) { statements; } //Defining constructor outside the class className::className(parameters) { statements; }
Example:
In the example below, a class called Circle is created. A constructor is also created which is used to initialize the member variable called radius of the class.
#include <iostream> using namespace std; class Circle { public: int radius; float area() { return 22/7.0*radius*radius; } Circle(int); }; //constructor definition Circle::Circle(int x) { radius = x; } int main (){ Circle Cir1(5); Circle Cir2(10); cout<<Cir1.area()<<"\n"; cout<<Cir2.area()<<"\n"; return 0; }
The output of the above code will be:
78.5714 314.286
Constructor Overloading
Like functions, a constructors can also be overloaded in C++. With constructor overloading feature in C++, two or more constructors can be created in the same class with different definitions like different number and types of parameters. The compiler automatically calls the constructor which matches the argument passed while creating the object.
Example:
In this example two constructors are created. The first constructor (default constructor) takes no parameters and the second constructor takes one parameter to initialize an object of the class Circle.
In the main function, two objects of class Circle are created: Cir1 and Cir2. Cir1 uses default constructor to initialize the object while the Cir2 uses the constructor that takes one parameter to initialize the object.
#include <iostream> using namespace std; class Circle { public: int radius; float area() { return 22/7.0*radius*radius; } Circle(); Circle(int); }; //constructor without parameter Circle::Circle() { radius = 1; } //constructor with one parameter Circle::Circle(int x) { radius = x; } int main (){ //syntax for calling default constructor Circle Cir1; Circle Cir2(10); cout<<Cir1.area()<<"\n"; cout<<Cir2.area()<<"\n"; return 0; }
The output of the above code will be:
3.14286 314.286
A constructor is called default constructor, if it takes no arguments to initialize the object. Please note down the syntax to initialize an object using default constructor in the above example.