Just a quick question.
I've written some code that returns a custom class Command, and the code I've written seems to work fine. I was wondering if there are any reasons that I shouldn't be doing it this way. It's something like this:
Command Behavior::getCommand ()
{
char input = 'x';
return Command (input, -1, -1);
}
Anyway, I read that constructors aren't meant to have a return value, but this works in g++.
Thanks for any advice,
Rhys
You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.
No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
A constructor cannot have a return type (not even a void return type). A common source of this error is a missing semicolon between the end of a class definition and the first constructor implementation. The compiler sees the class as a definition of the return type for the constructor function, and generates C2533.
A constructor returns a new instance of the class it belongs to, even if it doesn't have an explicit return statement.
The constructor itself doesn't have a return value. What this does is constructs a temporary Command
object and returns the constructed objet to the caller. It's effectively the same as if you said:
Command temp(input, -1, -1);
return temp;
It will work on any C++ compiler.
getCommand
isn't a constructor. The above is perfectly valid, and also generally efficient, due to thre return-value optimisation (RVO), which (I think) wouldn't apply if you instantiated a local variable and returned that.
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