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.
C++ Programming – Why Explicitly Call a Constructor
c++constructor
Best Answer
You also sometimes explicitly use a constructor to build a temporary. For example, if you have some class with a constructor:
and a function
but you don't have a Foo around, you could do
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
no matter what you do. But you can invoke a constructor without allocating memory - that's what placement new is for.
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.