简体   繁体   中英

When is a copy constructor called in c++, is not it called when I assign a object to another object?

class Myinteger(){
    public:
      Myinteger( int len );             // simple constructor
      Myinteger( const Myinteger &obj);  // copy constructor
      ~Myinteger();                      // destructor
    private:
      int *ptr;   
}

Myinteger::Myinteger(const Myinteger &obj) {
  cout << "Copy constructor allocating ptr." << endl;
  ptr = new int;
  *ptr = *obj.ptr; // copy the value
}

int main(){
   Myinteger obj1(10);
   Myinteger obj2(20);
   obj1=obj2;
   return 0;
}

Copy constructor is not called when assigning obj2 to obj1, I confirm it since "Copy constructor allocating ptr." is not printed to the console,

So if copy constructor is not called which method is called in the above case when assigning obj2 to obj1 , also tell in which cases copy constructors of a class is called.

A copy constructor, such as would be declared thus:

Myinteger(const Myinteger& other);

would be used as either

Myinteger obj2 = obj1;

or

Myinteger obj2(obj1);

but an assignment operator, declared as:

Myinteger& operator =(const Myinteger& other);

would be used where your code has

Myinteger obj2;
obj2 = obj1;

This is what you have in your code, so the assignment operator is being called, and not the copy constructor.

In this statement

obj1=obj2;

there is used the copy assignment operator because the both operands (objects) of the assignment were already created. So if they are already created neither constructor will be called.

If you want to use the copy constructor then you could write for example

int main()
{
   Myinteger obj1( "10" );
   Myinteger obj2 = obj1;

   return 0;
}

i got the answer, what i thought is that copy constructor is called when ever we assign an object to another object which is conceptually wrong. copy constructor is called only when an object is created, if we assign an object to already existing object then overloaded assignment operator function is called, otherwise default assignment operator function is called from the class.

I got the answer, what I thought is that copy constructor is called when ever we assign an object to another object which is conceptually wrong. copy constructor is called only when an object is created, if we assign an object to already existing object then overloaded assignment operator function is called, otherwise default assignment operator function is called from the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM