C++ Copying and Copy constructors
-
How copying works
If you declare some variable for example a and set variable b to a you are copying a by value.
int a = 5; int b = a;
They are independent variable. If you change a on runtime of program b will stay the same but if you do this on pointers you will not copy value of pointer but memory adress it points to.
int* a = new int; int* b = a; // it will point at the same adress as a
If you do something on b it will affect also a.
*b = 3;
-
What is copy constructor
Copy constructor is a constructor that takes another object of the same class and makes new object out of it. It copies all members to a new object.
-
How to write copy constructor
Constructor gets the const reference of another object of that class. Const because we dont modify another object, we just get the values. For example we have an Entity class with private ints m_X and m_Y.
class Entity{ private: int m_X, m_Y; };
We add default constructor and getters
class Entity{ private: int m_X, m_Y; public: Entity(int x, int y) : m_X(x), m_Y(y) {} int GetX() const{ return m_X; } int GetY() const{ return m_Y; } };
Then we add another constructor that will be our copy constructor. It gets
Entity
type parameter named another.class Entity{ private: int m_X, m_Y; public: Entity(int x, int y) : m_X(x), m_Y(y) {} Entity(const Entity& another) : m_X(another.getX()), m_Y(another.getY()) {} int GetX() const{ return m_X; } int GetY() const{ return m_Y; } };
and now we can use another object to make a new object from entity class
Entity e1(5, 2); Entity e2 = e1;
They will have the same values and they will be independent from themselves