top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between a copy constructor and an overloaded assignment operator?

+5 votes
488 views
What is the difference between a copy constructor and an overloaded assignment operator?
posted Nov 14, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+3 votes

Objective of both is same.
Copy constructor is called at the time of initialization of an object from another existing object. Whereas assignment operator is being called at the time of assignment.
For Ex:
A a;
A b(a); /* copy constructor called*/

b = a; /* operator overloading of = */

answer Nov 14, 2013 by Vimal Kumar Mishra
Adding a better example

class Cents
{
private:
    int m_a;
public:
    //
    Cents(int a=0)
    {
        m_a = a;
    }
 
    // Copy constructor
    Cents(const Cents &c)
    {
        m_a = c.m_a;
    }

   cents& operator= (const Cents &c)
   {
      // do the copy
      m_a = c.m_a;
      // return the existing object
      return *this;
    }
};

Now
cent abc(a) // Copy Constructor is called
abc = a // Assignment operator is called
+2 votes

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Copy constructors are called in following cases:

(a) when a function returns an object of that class by value .
(b) when the object of that class is passed by value as an argument to a function .
(c) when you construct an object based on another object of the same class .
(d) When compiler generates a temporary object .

answer Nov 19, 2013 by Vikas Upadhyay
...