Copy constructor

suggest change

Copy constructor on the other hand , is the complete opposite of the Assignment Constructor. This time, it is used to initialize an already nonexistent(or non-previously initialized) object. This means it copies all the data from the object you are assigning it to , without actually initializing the object that is being copied onto. Now Let’s take a look at the same code as before but modify the assignment constructor to be a copy constructor :

#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; 
    }

    int data;
};

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

You can see here Foo foo2 = foo; in the main function I immediately assign the object before actually initializing it, which as said before means it’s a copy constructor. And notice that I didn’t need to pass the parameter int for the foo2 object since I automatically pulled the previous data from the object foo. Here is an example output : http://cpp.sh/5iu7

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Copying vs assignment:
* Syntax
* Copy constructor

Table Of Contents
8 Arrays
11 Loops
39 Streams
47 Copying vs assignment
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype