0

Example class:

class myclass
{
  int a;
  int b;

public:
  myclass() {}
  myclass(int x, int y)
  {
    a = x;
    b = y;
  }
};

Function:

myclass function()
{
  return myclass(2, 3);
}

This line I do not understand:

 return myclass(2, 3);

How is it possible to return object like this? Looks like copy constructor is being used but constructors shouldn't return any value? (c++ beginner language please)

B0rn4
  • 9
  • 1
  • 4
  • 2
    Not sure what you don't understand. It is creating a `myclass` object by calling constructor, and then returning that object from `function()`. – Cody Gray - on strike Aug 27 '17 at 14:54
  • `myclass(2, 3)` does, sort of, return a class object. For example you can do `myclass A = myclass(2, 3);`. It is handing over the address. – Error - Syntactical Remorse Aug 27 '17 at 14:56
  • First time I stumbled upon syntax like 'class_name(..)' to find out it returns object? Never saw it being used in any of mine c++ beginner books. – B0rn4 Aug 27 '17 at 15:03
  • class_name(...) is a call to the constructor. Notice that the constructor has exactly that name where it is defined in the class definition. – Cody Gray - on strike Aug 27 '17 at 15:07
  • Thanks, now I at least learned that expressions such as 'myclass obj = myclass(2,3)' or 'myclass *ptr = &(myclass(2,3));' are valid in C++ – B0rn4 Aug 27 '17 at 15:21

3 Answers3

1

The return statement has a specific syntax: return expression where expression is convertible to the function return type.

So myclass(2, 3) is convertible to the return type (it is the same type). You could also have used return {2,3};.

From the link we also note:

Returning by value may involve construction and copy/move of a temporary object, unless copy elision is used.

wally
  • 10,717
  • 5
  • 39
  • 72
1

The statement

return myclass(2, 3);

does two things:

  1. First a temporary object is created. This is what myclass(2, 3) does. It creates an object, calling the appropriate constructor.

  2. The temporary object is returned, by value which means it's copied (or more likely the copy is elided as part of return value optimizations).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

myclass(2, 3) is an expression that evaluates to a new (temporary) object of type myclass, constructed by invoking the myclass::myclass(int, int) constructor.

return myclass(2, 3); uses the value of such expression (the newly constructed myclass) as return value of function function. This in turn possibly invokes a copy constructor to copy the value from the temporary location where it has been constructed to whatever location is used for the return value (unless RVO kicks in, which should be mandatory in some recent C++ standard).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299