mercredi 1 août 2018

Unable to access subclass methods from baseclass pointer

Not sure where my inheritance went wrong here, but I seem to be only able to access the methods of the baseclass when storing a subclass instance in a baseclass pointer:

class Car
{
    public:
        Car():type("Car") {};
        Car(const char* t):type(t) {};
        void get_type() const { return this->type; };
    private:
        std::string type;
};

class Ford : public Car
{
    public:
        Ford():Car("Ford"), doors(4) {};
        Ford(int x):Car("Ford"), doors(x) {};
        void get_doors() const { return this->doors; };
    private:
        int doors;
};

int main()
{
    Car* c = nullptr;
    c = new Ford();
    c->get_doors(); // doesn't exist, only allows for get_type()
}

It's very likely it could be a misuse of the pointer. I'll admit that C++ is not my strong suit so I am trying to replicate a program written in Python that heavily uses inheritance but it's much less complicated than writing it in C++ since you don't have explicit use of Pointers and References (at the abstract level that is).

Aucun commentaire:

Enregistrer un commentaire