Hi all,
I have troubles with a kind of copy-constructor.
Let's say we want to create a car with 4 wheels.
So first we declare the class Wheel:
Code:
class Wheel
{
public:
Wheel(); // Constructor
Wheel(const Wheel&); // Copy-constructor
~Wheel(); // Destructor
}
Now we declare the class Car:
Code:
class Car
{
public:
Car(int numberOfWheels); // Constructor (specifies the number of wheels of the car)
Car(const Car&); // Copy-constructor
~Car(); // Destructor
private:
int numberOfWheels; // Number of wheels
Wheel* wheels; // Composition: here will be multiple 'Wheel' objects (dynamically alocated)
}
Now the definition of the Car constructor looks like this:
Code:
Car::Car(int numberOfWheels) : numberOfWheels(numberOfWheels)
{
wheels = new Wheel[numberOfWheels]; // Dynamic allocation of wheels
}
So finally let's go to create some car:
Code:
int main()
{
Car car1(4); // We have created a car with 4 wheels
}
And here are the steps of the car creation:
1. Car constructor is called.
2. Wheel constructor is called 4-times.
And now we would like to copy the existing car to some another car. So we can say:
Code:
int main
{
Car car1(4); // We have created a car with 4 wheels
Car car2 = car1;
}
Now the copy-constructor should be called for the copying process (also Car copy-constructor, also Wheel copy-constructors). Thus the Car copy-constructor should also copy the 4 wheels from the old car.
But my question is:
=============================================
What should the Car copy-constructor look like?
=============================================
Code:
Car::Car(const Car&)
{
.
. ???
.
}
Thanks.
Petike