Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything wrong with returning default constructed values?

Suppose I have the following code:

class some_class{};

some_class some_function()
{
    return some_class();
}

This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?

like image 746
Jason Baker Avatar asked Sep 18 '08 20:09

Jason Baker


People also ask

Why do constructors not return values Java?

Constructors return an instance of a class, so they can't have any other return values.

What is the purpose of default constructor?

A default constructor in Java is created by the compiler itself when the programmer doesn't create any constructor. The purpose of the default constructor is to initialize the attributes of the object with their default values.

Why there is no return type for constructor in C++?

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.

Can default constructor have parameters?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


2 Answers

No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.

like image 89
1800 INFORMATION Avatar answered Nov 10 '22 07:11

1800 INFORMATION


Returning objects from a function call is the "Factory" Design Pattern, and is used extensively.

However, you will want to be careful whether you return objects, or pointers to objects. The former of these will introduce you to copy constructors / assignment operators, which can be a pain.

like image 5
RichS Avatar answered Nov 10 '22 06:11

RichS