1
#include <bits/stdc++.h>
using namespace std;
class vec{
public:
    int x;
    int y;
    vec(int a, int b)
    {
        x = a; y = b;
    }
    vec operator+(vec that)
    {
        vec ans(0, 0);
        ans.x = this->x + that.x;
        ans.y = this->y + that.y;
        return ans;
    }
};
int main()
{
    vec a(0, 1);
    a = a + vec(2, 3); // how does this line work
    printf("%d %d\n", a.x, a.y);
    return 0;
}

everyone says the constructor does not return anything. it looks like it is returning an object. i tried looking for temporary or unnamed objects but could not find anything specific to this kind of expressions.

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
  • The implementation (aka compiler) ensures the constructor is called when initialising objects. Practically, when it sees an expression that requires initialisation of an object, the compiler emits code that takes care of what is needed - ensuring there is memory to represent the object, calling the constructor to initialise that memory, etc – Peter Aug 26 '20 at 06:16
  • 1
    [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) – Jesper Juhl Aug 26 '20 at 06:20
  • 1
    [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/5910058) – Jesper Juhl Aug 26 '20 at 06:21

2 Answers2

1

The constructor is a special function that initializes the object in memory. The object may be on the stack or the heap. Calling the constructor will initialize the memory. Note that the constructor is c++ syntactic sugar.

vec x(0, 1);                 // creates the object named x of type vec on the stack
vec *px = new vec(2, 3);     // creates the object pointed by px on the heap

x = x + vec(2, 3);           // vec(2, 3) creates a temporary object on stack 
                             // and initializes it with the parameters. 
                             // The overloaded operator+ on the object x is called, 
                             // passing the temporary object as the formal parameter
                             // 'that' of operator+ and it returns a temporary object
                             // on the stack that is copied back into the variable x
                             // as a result of the = assignment operation
vvg
  • 882
  • 2
  • 15
0

constructors "return" an instance of the class they are modeling so when you do

x = Foo(0,0);

x is assigned with the new object Foo returned by the constructor

so when you do

vec a(0, 1);
a = a + vec(2, 3); // how does this line work
printf("%d %d\n", a.x, a.y)

is "equivalent" to do

vec a(0, 1);
b = vec(2,3);
a = a + b;
printf("%d %d\n", a.x, a.y)
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83