2

Possible Duplicate:
Copy Constructor is not invoked

 # include <iostream>

 using namespace std;

class Abc
{

        public:
        int a;
        Abc()
        {
           cout<<"def cstr\n";
           a=10;
        }


        Abc(const Abc &source)
        {   
                a=source.a;
                cout<<"copy constructor is called"<<endl;
        }


};

int main()

{

    Abc  kk = Abc();
    cout<<kk.a<<endl;
         return 0;
}

In the above program my output is :

def cstr

10

Here I expected that copy constructor would be called after the default contructor which is not happening.

Please tell me whats going on here. Is it because Abc() is creating a temp object ??

Please correct me if I am wrong.

thanks !!!

Community
  • 1
  • 1
Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54

1 Answers1

1

Your copy constructor is ok, try that

   int main() {

       Abc  kk;
       Abc kk1 = kk;
       cout<<kk.a<<endl;
            return 0;
    }

Copy constructor is called once on construction from another existing object. Other times assignment operator is called. By saying Abc kk = Abc(); you are just calling default constructor.

Dmitriy Kachko
  • 2,804
  • 1
  • 19
  • 21