Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 returns 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?

like image 533
Invisible Hulk Avatar asked Nov 23 '10 04:11

Invisible Hulk


3 Answers

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.

like image 96
James McNellis Avatar answered Sep 19 '22 18:09

James McNellis


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.

like image 22
bill Avatar answered Sep 21 '22 18:09

bill


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

like image 43
Alok Save Avatar answered Sep 20 '22 18:09

Alok Save