I begin with C++ and I have trouble to use the polymorphism, especially when I want to use it in constructors of a new class. I know the issue has been treated here but I did not understand and my case is a little bit different.
To understand how to use it I built this little program. Here is the main.cpp
:
#include <iostream>
#include <string>
#include <headers.h>
using namespace std;
void Display(Car &c)
{
c.Show();
}
int main()
{
Car Clio(50);
SportCar Ferrari(200,200);
Clio.Show();
Ferrari.Show();
Display(Ferrari);
Race(Ferrari, Track());
return 0;
}
The headers.h
file :
#ifndef CAR_H
#define CAR_H
class Car
{
public:
Car(double s);
Car();
virtual void Show() const;
protected:
double m_Speed;
private:
};
#endif // CAR_H
#ifndef SPORTCAR_H
#define SPORTCAR_H
class SportCar : public Car
{
public:
SportCar(double s, double p);
SportCar();
virtual void Show() const;
protected:
private:
double m_Price;
};
#endif // SPORTCAR_H
#ifndef TRACK_H
#define SPORTCAR_H
class Track
{
public:
Track(double l);
Track();
protected:
private:
double m_Length;
};
#endif // SPORTCAR_H
#ifndef RACE_H
#define RACE_H
class Race
{
public:
Race(const Car& , Track t);
protected:
Car &m_Car;
Track m_Track;
private:
};
#endif // RACE_H
And finally, the src.cpp
file :
#include <string>
#include <iostream>
#include <headers.h>
using namespace std;
Car::Car(double s)
{
m_Speed = s;
}
Car::Car()
{
m_Speed = 50;
}
void Car::Show() const
{
cout << "I'm a car" << endl;
}
SportCar::SportCar(double s, double p) : Car(s)
{
m_Price = p;
}
SportCar::SportCar() : Car()
{
m_Price = 200;
}
void SportCar::Show() const
{
cout << "I'm a sportcar" << endl;
}
Track::Track(double l)
{
m_Length = l;
}
Track::Track()
{
m_Length = 10;
}
Race::Race(const Car& c, Track t)
{
m_Car = c;
m_Track = t;
m_Car.Show();
}
In summary I have two differents classes of car, one of which (SportCart
) inherits from the other (Car
) with two differents Show()
methods. And I have a class Race
whose members are a kind of car and a Track
. When I use the Race
constructor I can't pass in argument the car as a SportCar
.
In result I have :
I'm a car
I'm a sportcar
I'm a sportcar
I'm a car
And I want :
I'm a car
I'm a sportcar
I'm a sportcar
I'm a sportcar
I try to use references like that :
protected:
Car &m_Car;
Track m_Track;
But it doesn't work either, I have this error I can't fix :
||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
E:\documents\c++\test\src\src.cpp||In constructor 'Race::Race(const Car&, Track)':|
E:\documents\c++\test\src\src.cpp|46|error: uninitialized reference member in 'class Car&' [-fpermissive]|
include\headers.h|66|note: 'Car& Race::m_Car' should be initialized|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Thank you for your help.