Constructors
Constructor is used for initializing an object
Constructor will have same name as class name
It will not have a return type
It is called when object is created
It can be overloaded
It can take default arguments
If it is not defined then class will generate a default constructor
Types of constructors
Default constructor (provided by compiler if any constructor is not defined by programmer)
Non parameterized constructor
Parameterised constructor
Copy constructor
In copy constructor, argument must be passed by reference to avoid infinite recursion.
Copy Constructor
Copy Constructor is called only when a new object is instantiated.
Shallow Copy
A shallow copy copies the data as-is.
If your class has pointers, only the pointer value (address) is copied, not what it points to.
Two objects end up pointing to the same memory.
Memory:
Why this is bad ?
When one object is destroyed:
Memory gets freed
The other object still points to it
Boom: double delete / dangling pointer / undefined behavior
Deep Copy
A deep copy duplicates the actual data, not just the pointer.
Each object gets its own memory. No sharing.
Memory: