开发者

What does a constructor return?

My question is what does a constructor return? This question is not quite different from "What is the return type of a constructor?" I have read somewhere that a constructor r开发者_如何学编程eturns a complete object implicitly (i.e implicit return type is the name of the class) but it shall not be specified explicitly.

struct empty{};

int main(){
   empty(); //creates a temporary and implicitly a constructor is called
}

So as per my interpretation the implicit return type should be the name of the class, in this case empty. Is my wild interpretation correct?


A constructor doesn't return anything. A constructor is called to initialize an object. A constructor can only be used to initialize an object; you can't actually call a constructor explicitly (for one thing, constructors do not have names).

In the example you give, empty() is not a function call expression, it is value initialization. It creates a value-initialized temporary object of type empty.


construct does return something. it returns reference to object that this points to. so the implicit return statement from a constructor looks like

*this;

How is this used?

If you create a class template of something with a "generic" type as member, you call the default zero parameter constructor of the generic type explicitly (i.e., generic() ) in the constructor of your class something and initialize your generic member via the assignment operator and initialization statement of the something constructor. Constructor has to return something or none of that crap I just wrote would work. It's in the book I'm reading...lol.


Constructors do not return anything.
Constructors are called implicitly while object creation to initialize the object being created.


A constructor doesn't return anything.

Source of confusion:

Book *b = new Book();

Many are confused by the above code, which creates an illusion that the constructor returns a pointer to the newly created object.

When you use new keyword, the compiler allocates required memory and then calls the constructor to create a new object on the allocated memory. Then new returns the pointer to that memory block. The constructor only creates the object and never returns anything.


In C++, if I remember correctly, your code will allocate enough room for an "empty" on the stack, and then call empty's default constructor--as specified by the ()--implicitly passing it a this reference. There is no return. And in your case there is no constructor.


what about this:

int main() {
const empty &er = empty();
empty *ep = const_cast<empty*>(er); //casting away conentness to make changes in the members
cout<<"\n main ends \n";
//dtor get called here
}

ctor returns a const reference to a memory location(*this), you can cast away the const and use its as a nonconst normal object like empty *e = new e;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜