L.Maple
L.Maple

Reputation: 141

I am very confused about why return a constructor in C++ is legal

For example:

#include<iostream>
using namespace std;
class exa{
   private:
     int a;
  public:
    exa(int b = 0):a(b){}
    exa Add(exa obj){ return exa(a+obj.geta() ); }  //What happened over     there?
    int geta(){return a;}
};
int main()
{
   exa c1(2),c2;
   c2.Add(c1);
   cout << c2.geta() << endl;
  return 0;
}

Upvotes: 0

Views: 53

Answers (1)

szym
szym

Reputation: 5846

Note that you are passing arguments to the constructor. So you are not returning a constructor, but rather calling it to construct an object of the class. Because you are not using new, storage for the object is allocated on the stack.

Here, the method Add is returning (by value) an object of class exe.

In practice, the way it is used in your main, it does not do anything really, because the result of c2.Add(c1) is ignored.

If you wrote c2 = c2.Add(c1) then the new object would be copied (using default assignment operator=) into c2, and you should see output 2.

Upvotes: 1

Related Questions