1

why is copy constructor not being called for the return call of function func in the last lines of main function ..it is being called when i send a parameter by value but not when i am returning a value

class A
    {
        public:
        int x , y , z;
        A(int x=4 , int y=2 , int z=1)
        {
            this->x = x;
            this->y = y;
            this->z = z;
        }

        A(A& a)
        {
            x = a.x;
            y = a.y;
            z = a.z;
            printf("Copy Constructor called\n");
            a.x++;
        }

        //not a copy constructor
        A(A *a)
        {
            x = a->x;
            y = a->y;
            z = a->z;
            printf("Some Constructor called\n");
            (a->x)++;
        }
        void tell() { printf("x=%d y=%d z=%d\n" , x , y , z);}
    };

    A func()
    {
    A a;

    return a;
    }

    int main()
    {
        A a1;

        a1=func(); //why is copy constructor not called while returning
        a1.tell();
        return 0;
    }
Saransh
  • 109
  • 1
  • 8

1 Answers1

3

This is because of copy-elision. The compiler is allowed to omit the copy and store the result directly in the object. You can turn off copy-elision with the compiler option -fno-elide-constructors (I wouldn't recommend it though).

Related: What are copy elision and return value optimization?

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253