views:

118

answers:

4

Hi, 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

+7  A: 

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.

James McNellis
Thanks for that! Glad I don't have to rewrite it, it's nice functionality.
Fecal Brunch
+2  A: 

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.

Marcelo Cantos
Duly noted, cheers!
Fecal Brunch
Under many circumstances, local variables can be retured sans-copy constructor as well.
Dennis Zickefoose
Which is called Named Return Value Optimization, or NRVO.
GMan
Thanks for the feedback, guys. I wasn't aware of NRVO.
Marcelo Cantos
+1  A: 

The constructor doesn't have a return value; you're explicitly constructing a temporary instance of the class, and returning that. There's nothing wrong with this, other than it will make a copy.

If you want to avoid the copy, you have a few options, one of which is to have an out parameter which is a Command* and use new and delete.

jeffamaphone
A: 

You don't have a constructor with a return value. Command::Command(char, int, int) is your constructor.

You have a method which returns an object, which is perfectly normal.

Brian Roach