DEV Community

Aniket Chandrakant Dhole
Aniket Chandrakant Dhole

Posted on

Constructors in C++

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);
Enter fullscreen mode Exit fullscreen mode

};

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)

Collapse
 
pgradot profile image
Pierre Gradot

it is always public

Constructors can be private or protected too ;)

Collapse
 
aniket1004 profile image
Aniket Chandrakant Dhole

Is it really useful?

Collapse
 
pgradot profile image
Pierre Gradot • Edited

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

Thread Thread
 
aniket1004 profile image
Aniket Chandrakant Dhole

Thank you for sharing ...

Collapse
 
dynamicsquid profile image
DynamicSquid

implicitly called

You could also explicitly call it:

Hello obj = Hello(2, 3);
Enter fullscreen mode Exit fullscreen mode