Answer to Question #156487 in C++ for 0

Question #156487

Create an abstract class Car (model, price). Include get and set methods

form these fields. The setPrice Method must be abstract.


1
Expert's answer
2021-01-19T01:57:27-0500

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
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog