Create an abstract class Car (model, price). Include get and set methods
form these fields. The setPrice Method must be abstract.
car.h (header file):
#ifndef CAR_H
#define CAR_H
#include <string>
class Car
{
public:
Car();
/*destructor should be virtual for base class otherwise in some cases
when deleting derived class objects their destructor won't be called
which can lead to memory leaks*/
virtual ~Car();
//get/set methods for model
std::string getModel() const;
void setModel(const std::string &m);
//get/set methods for price
int getPrice() const;
//abstract '= 0' method, needs to be virtual
virtual void setPrice(int p) = 0;
private:
std::string model;
protected:
/*price defined as protected so derived classes would be able
to use it in their setPrice definition*/
int price;
};
#endif // CAR_H
car.cpp (source file):
#include "car.h"
Car::Car()
{
}
Car::~Car()
{
}
std::string Car::getModel() const
{
return model;
}
void Car::setModel(const std::string &m)
{
model = m;
}
int Car::getPrice() const
{
return price;
}
And small example how derived class can use it:
//derived class constructor, takes model and price as parameters
SportCar::SportCar(const std::string m, int p)
{
setModel(m); //calls setModel version from base class
setPrice(p); //calls setPrice version from SportCar class
}
Comments
Leave a comment