A constructor in C++ is a method that is implicitly called when an object of a class is created.
The constructor has the same name as the class, it is always public, and it does not have any return value.
When memory is allocated for object after that constructor is called.
Example
class Hello
{
public:
Hello()
{ // Constructor
cout << "Hello";
}
};
int main()
{
Hello myObj;
return 0;
}
constructors can also be defined outside the class.
class Hello
{
public:
int x;
int y;
Hello(int x, int y);
};
Hello::Hello(int a,int b) {
x = a;
y = b;
}
int main()
{
Hello hobj(10,20);
return 0;
}
Constructors can be useful for setting initial values for attributes.
Top comments (5)
Constructors can be private or protected too ;)
Is it really useful?
Yes.
It is mandatory to have a private constructor implement the singleton design pattern (which is a pattern I quite highly discourage). See codereview.stackexchange.com/a/173935
A protected constructor is a way to create an abstract class. See stackoverflow.com/questions/105722...
Prior to C++11, private constructors were part of the technique to make classes uncopyable. See stackoverflow.com/a/2173764/12342718
Thank you for sharing ...
You could also explicitly call it: