Home »
C++ programming language
What is the Constructor and its types in C++?
Learn: What is the constructor in C++ programming language? Types of constructors in C++, Explain constructors with examples.
What is the Constructor in C++?
Constructor is the special type of member function in C++ classes, which are automatically invoked when an object is being created. It is special because its name is same as the class name.
Why Constructor is Used?
Constructor is used for:
- To initialize data member of class: In the constructor member function (which will be declared by the programmer) we can initialize the default vales to the data members and they can be used further for processing.
- To allocate memory for data member: Constructor can also be used to declare run time memory (dynamic memory for the data members).
What are the Properties of Constructor?
There are following properties of constructor:
- Constructor has the same name as the class name. It is case sensitive.
- Constructor does not have return type.
- We can overload constructor, it means we can create more than one constructor of class.
- We can use default argument in constructor.
- It must be public type.
Example of C++ Constructor
#include <iostream>
using namespace std;
class Sample {
private:
int X;
public:
// default constructor
Sample() {
// data member initialization
X = 5;
}
void set(int a) { X = a; }
void print() { cout << "Value of X : " << X << endl; }
};
int main() {
// Constructor called when object created
Sample S;
S.print();
// set new value
S.set(10);
S.print();
return 0;
}
Output
Value of X : 5
Value of X : 10
Types of C++ Constructors
Normally Constructors are following type:
- Default Constructor or Zero argument constructor
- Parameterized constructor
- Copy constructor
- Conversion constructor
- Explicit constructor
Note:
If we do not create constructor in user define class. Then compiler automatically insert constructor with empty body in compiled code.