1

I was just looking into C++ OOP basics and actually surprised after trying this:

class A {
public:
    A() :i(10), j(20) { cout << "constructor " << endl; }
    A(const A &obj)
    {
        cout << "copy constructor" << endl;
    }
    int i;
    int j;
    ~A() { cout << "destructor " << endl; }
};

A func()
{
    A loc;
    cout<<&loc<<endl;
    return loc;
}

int main()
{
    A obj = func();
    cout<<&obj<<endl;
}

I ran the above code using g++ (GCC) 4.8.5

The output is:

constructor 10
0x71a5b3354010
0x71a5b3354010
destructor 10

Here, First,I was expecting copy constructor to be called. But it didn't (when ran with MSVC++ 14.0 it did). And how could be the local object in main() be the same as the object in func() (it gave the same object address)?

I'm just a beginner in C++ and couldn't understand that behaviour. Please clarify!!!

infinite loop
  • 1,309
  • 9
  • 19

0 Answers0