C++ Programming – Why Explicitly Call a Constructor

c++constructor

I know we can explicitly call the constructor of a class in C++ using scope resolution operator, i.e. className::className(). I was wondering where exactly would I need to make such a call.

Best Answer

You also sometimes explicitly use a constructor to build a temporary. For example, if you have some class with a constructor:

class Foo
{
    Foo(char* c, int i);
};

and a function

void Bar(Foo foo);

but you don't have a Foo around, you could do

Bar(Foo("hello", 5));

This is like a cast. Indeed, if you have a constructor that takes only one parameter, the C++ compiler will use that constructor to perform implicit casts.

It is not legal to call a constructor on an already-existing object. That is, you cannot do

Foo foo;
foo.Foo();  // compile error!

no matter what you do. But you can invoke a constructor without allocating memory - that's what placement new is for.

char buffer[sizeof(Foo)];      // a bit of memory
Foo* foo = new(buffer) Foo();  // construct a Foo inside buffer

You give new some memory, and it constructs the object in that spot instead of allocating new memory. This usage is considered evil, and is rare in most types of code, but common in embedded and data structure code.

For example, std::vector::push_back uses this technique to invoke the copy constructor. That way, it only needs to do one copy, instead of creating an empty object and using the assignment operator.

Related Question