I am a beginner and tryed to find an answer on this website but I was not able to figure out how to solve my specific C++ OOP problem.
Short: I want to access and change values of a parent class from subclass instances, but somehow my approach seems not to be working.
Example: There are many Car
instances in my program (created with new construct). If one of the Car
objects detects a collision, all Car
instances should inverse their movement. The Car
that registered the collision should call the parents' ChangeSpeed
method or change the speed
value directly.
Problem: the speed variable seems not to be updated. Is there something wrong with this particular code/ approach or do I have to search for my problem somewhere else?
// SpeedControl.h ------------------------------
class SpeedControl
{
public:
void ChangeSpeed(int);
protected:
int speed;
};
class Car:
public SpeedControl
{
public:
void MoveCar();
void DetectCollision();
private:
int position;
};
// SpeedControl.cpp ------------------------------
#include SpeedControl.h
SpeedControl::SpeedControl(void)
{
speed = 10;
}
SpeedControl::~SpeedControl(void)
{
}
SpeedControl::ChangeSpeed(int _value)
{
speed *= _value;
}
// Car.cpp ------------------------------
#include SpeedControl.h
Car::Car(void)
{
position = 100;
}
Car::~Car(void)
{
}
Car::MoveCar()
{
position += speed; // speed should be accessible?
}
Car::DetectCollision()
{
speed *= (-1); // inverse speed variable in parent class to inverse direction of ALL cars
// alternative:
// ChangeSpeed(-1); // call parent function to inverse speed
}