Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why explicitly call a constructor in C++

Tags:

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.

like image 213
Arnkrishn Avatar asked May 06 '09 00:05

Arnkrishn


People also ask

What happens when we call a constructor explicitly?

When the constructor is called explicitly the compiler creates a nameless temporary object and it is immediately destroyed.

Is there a need to call a constructor function explicitly?

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation. The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class.

What is meant by explicit call?

Explicit means done by the programmer. Implicit means done by the JVM or the tool , not the Programmer. For Example: Java will provide us default constructor implicitly.Even if the programmer didn't write code for constructor, he can call default constructor.

How are constructors called implicitly and explicitly?

The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method. Example e = Example(0, 50); // Explicit call. Example e2(0, 50); // Implicit call.


1 Answers

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.

like image 124
Charlie Avatar answered Oct 03 '22 13:10

Charlie