Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a constructor for return

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

like image 371
Rhys van der Waerden Avatar asked Apr 15 '10 03:04

Rhys van der Waerden


People also ask

Can you have a return in a constructor?

You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.

Can we use return in constructor Java?

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.

Why return type is not allowed for constructor?

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.

What should a constructor return?

A constructor returns a new instance of the class it belongs to, even if it doesn't have an explicit return statement.


2 Answers

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.

like image 161
James McNellis Avatar answered Oct 04 '22 03:10

James McNellis


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.

like image 23
Marcelo Cantos Avatar answered Oct 04 '22 03:10

Marcelo Cantos