
February 16th, 2005, 09:56 PM
|
|
Contributing User
|
|
Join Date: Sep 2004
Posts: 37
Time spent in forums: 1 h 15 m 20 sec
Reputation Power: 5
|
|
|
Inheritance and copy constructors
The problem I am having is when I make a class that contains a pointer to a base class. Anytime you have memory that is dynamically allocated you must write your own copy constructors, but how do you copy a pointer if you don't know what child class has been used to allocate the memory. The following code should help put my problem into perspective. All definitions have been excluded aside from the Garage class assignment operator, which is where the problem area lies.
Code:
// Base class Vehicle
class Vehicle
{
public:
Vehicle();
virtual Vehicle()=0 { }
};
// Class car inherits from Vehicle
class Car : public Vehicle
{
public:
Car();
~Car();
};
// Class Truck inherits from Vehicle
class Truck : public Vehicle
{
public:
Truck();
~Truck();
};
// Class Garage contains a pointer to a Vehicle
class Garage
{
public:
Garage
Garage( const Garage rhv );
Garage
Garage& operator=( const Garage rhv );
void SetVehicle( Vehicle* pVehicle );
Vehicle* GetVehicle() const;
private:
Vehicle* m_pVehicle;
};
// Class Garage assignment operator
Garage& Garage::operator=( const Garage rhv )
{
if( this != &rhv )
{
// Copy the vehicle pointer
if( !m_pVehicle )
{
// Check if new memory needs to be allocated
if( rhv.m_pVehicle )
{
// The problem lies here when I want to allocate the new memory
// I dont know whether to allocate a truck or a car.
//m_pVehicle = new Car;
//m_pVehicle = new Truck;
*m_pVehicle = *rhv.m_pVehicle;
}
}
else
{
// Check if the vehicle should be removed
if( rhv.m_pVehicle )
*m_pVehicle = *rhv.m_pVehicle;
else
RemoveVehicle();
}
}
return *this;
}
int main()
{
Garage myGarage;
Car* pCar = new Car;
myGarage.SetVehicle( pCar );
Garage yourGarage;
yourGarage = myGarage;
return 0;
}
As you can probably see in the above code, the child type is unknown when trying to assign one Vehicle pointer to another. Now I know what your probably thinking, Runtime Type ID, or use a string member to hold the class type ie "Car" but I am curious to know if there is a more elegant solution to this problem. Let me know what ya think, for now I will just use a string member.
|