Ok we have briefly looked over what the copy constructor and assignment constructor are above and gave examples of each now let’s see both of them in the same code. This code will be similar as above two. Let’s take this :

#include <iostream>
#include <string>

using std::cout;
using std::endl;

class Foo
{
  public:
    Foo(int data)
    {
        this->data = data;    
    }
    ~Foo(){};
    Foo(const Foo& rhs)
    {
            data = rhs.data; 
    }

    Foo& operator=(const Foo& rhs)
    {
        data = rhs.data; 
        return *this;
    }

    int data;
};

int main()
{
   Foo foo(2); //Foo(int data) / Normal Constructor called
   Foo foo2 = foo; //Copy Constructor Called
   cout << foo2.data << endl;

   Foo foo3(42);
   foo3=foo; //Assignment Constructor Called
   cout << foo3.data << endl;
}

Output:

2
2

Here you can see we first call the copy constructor by executing the line Foo foo2 = foo; . Since we didn’t initialize it previously. And then next we call the assignment operator on foo3 since it was already initialized foo3=foo;