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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With