B0rn4
B0rn4

Reputation: 19

Returning object from function using constructor

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)

Upvotes: 1

Views: 4184

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409166

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).

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126777

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).

Upvotes: 0

wally
wally

Reputation: 11002

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.

Upvotes: 1

Related Questions