I have a problem regarding inheritance on C++. The Vehicle
class has SetStartingPosition()
and GetStartingPosition()
functions. The Car
class inherits these functions and sets the starting position to 5 in the constructor with SetStartingPosition(5)
.
What I want is that when a new vehicle (new Car
) is added to a lane (in the Lane
class) with the use of the AddVehicleToALane(Vehicle* vehicle)
function, the position of this Car
is assigned the value of 5.
Vehicle.h:
Class Vehicle{
public:
Vehicle();
Vehicle(double position);
virtual ~Vehicle();
void SetStartingPosition(double startingpos){
fStartingPos = startingpos
}
double GetStartingPosition(){
return fStartingPos;
}
private:
double fStartingPos;
}
Car.h:
#include "vehicle.h"
Class Car: public Vehicle{
public:
Car();
Car(double position);
}
Car.cpp:
Car::Car(double position): Vehicle(position){
SetStartingPosition(5);
}
Lane.h:
#include "vehicle.h"
#include "car.h"
Class Lane{
public:
void AddRandomVehicle();
void AddVehicleToALane(Vehicle* vehicle){
fVehicles.push_back(vehicle);
}
private:
std::vector<Vehicle*> fVehicles;
Vehicle *v;
}
Lane.cpp:
void Lane::AddRandomVehicle(){
int i = 0;
AddVehicleToALane(new Car(fVehicles[i]->GetStartingPosition()));
}
The final command v->GetStartingPosition()
doesn't work. Basically, when a new instance of Car
(new Car
) is created, I want this car to obtain the starting position = 5 (from car.cpp
), but the final command doesn't work.
Could anyone give me some tips as how to solve this? I don't think it should be too difficult, but I've spent hours trying to figure out and I can't solve it! Any help would be greatly appreciated.