skydoor
skydoor

Reputation: 25868

What is returned by the constructor in C++?

I know that there is no return type of the constructors in C++.

However, the code below compiles. What is returned by the constructor in the code below?

class A{

public:
A() {}
}


A a = A();      //what is returned by A() here, why?

Is there any conflict here?

Upvotes: 20

Views: 25380

Answers (3)

Shubham Tyagi
Shubham Tyagi

Reputation: 191

The only possible explanation I can come up is probably the compiler have augmented the code as :

A a = A();
/*
compiler generated code.
A a;
a.A::A();

a.A::~A();  destructor will also be inserted by compiler after "a" goes out of scope.
*/

There is no return type of constructor not even void because it is not required. Each member access inside constructor is done through "this" pointer so if constructor has a pointer on which it can perform its modification why it would require to return it.

P.S: Copy constructor was not called when I have tested the code. It may be possible that compiler have optimized the code and remove the requirement of calling copy constructor. If someone find the correct answer to this please let me know.

Upvotes: -1

AnT stands with Russia
AnT stands with Russia

Reputation: 320501

The syntax T(), where T is some type, is a functional-cast notation that creates a value-initialized object of type T. This does not necessarily involve a constructor (it might or it might not). For example, the int() is a perfectly valid expression and type int has no constructors. In any case, even if type T has a constructor, to interpret T() as "something returned from constructor" is simply incorrect. This is not a constructor call.

Upvotes: 3

avakar
avakar

Reputation: 32635

Nothing is returned from the constructor. The syntax A() is not a constructor call, it creates a temporary object of type A (and calls the constructor in the process).

You can't call a constructor directly, constructors are called as a part of object construction.

In your code, during the construction of the temporary the default constructor (the one you defined) is called. Then, during the construction of a, the copy constructor (generated automatically by the compiler) is called with the temporary as an argument.

As Greg correctly points out, in some circumstances (including this one), the compiler is allowed to avoid the copy-construction and default-construct a (the copy-constructor must be accessible however). I know of no compiler that wouldn't perform such optimization.

Upvotes: 23

Related Questions