Saturday 19 April 2014

Copy Constructor Dilemma: Is it possible to create a new object?

Consider the following lines of code
//ref1:
#ifndef __CAR_H__
#define __CAR_H__
#include <string.h>
class Car
{
private:
    Car& Object;
public:
    Car(Car& Obj):Object(Obj)
    {
    }
private:
    char color[20];
public:
    void setColor(char* color)
    {
        strcpy(this->color,color);
    }
    char* getColor()
    {
        return color;
    }
};
#endif


Since the class has defined a copy constructor only, it expects Car’s object to be passed to create any usable object. But we don’t have an object to create a new object. If this is the case then how do we create the first usable object of Car?
//ref2:

int main()
{
    Car object(object); // Is it ok? 
    object.setColor("blue");
    object.getColor();
}

How it works? When the statement on line number 5 is compiled, compiler will allocate memory of size Car. Which loader shall then map with actual memory of the system before executing program. This means memory segment has already been allocated before calling the constructor. Hence we have the address of uninitialized object Car.

Consequently we may pass the object to create a usable object of Car, as seen on line number 5 on ref2. And the compiler complies the program without complaining. As copy constructor requires an object reference of Car. This object being referred needn’t be initialized. Constructor doesn’t create the object, it only initializes the object calling the constructor.