-1

I'm trying to write a function parkVehicle(), this function has to access the read member function of the derived class through a Base class pointer. How can I access it?

class Parking {
     const int MAX_SPOTS_NO = 100;
    Base B[MAX_SPOTS_NO];
    void parkVehicle() const;

}


class Base : public Read {
    std::istream& read(std::istream& istr = std::cin);
}

class derived : public Base {
    std::istream& read(std::istream& istr = std::cin);
}


class Read{
virtual std::istream& read(std::istream& istr = std::cin) = 0; 
}



void parkVehicle() {
    //call read from the derived class
}
beebo
  • 1
  • 1
  • There are at least two fundamental C++ reasons why you can't. C++ objects simply don't work this way. You need to implement virtual inheritance, and you need to do something about object slicing. C++ is not Java. For more information, see your C++ textbook. – Sam Varshavchik Apr 11 '20 at 02:09
  • If you think you need to access a derived class member through a base class pointer, your design is very likely flawed. Back up a few steps and rethink your approach. (Possibly, you want a virtual function in your base class, but do review your approach to make sure the abstraction levels make sense.) – JaMiT Apr 11 '20 at 02:10

2 Answers2

0

As suggested in the comments, your class design needs to be revised. However, just for the shake of answering to your queries, you can modify like so - variable MAX_SPOTS_NO needs to be declared as static and the member variable B may be declared as pointer array ( prefer to use smart pointers instead) to avoid cyclic redundancy issue

class Base; // forward declaration

class Parking {
public:
    static const int MAX_SPOTS_NO = 100;
    Base* B[MAX_SPOTS_NO];
    void parkVehicle() ;

};

void Parking::parkVehicle() {
    //call read from the derived class
    B[0] = new Base();
    B[0]->read();
}
seccpur
  • 4,996
  • 2
  • 13
  • 21
0

Your array is slicing the objects, so there are no derived objects in the array, only Base objects. Polymorphism works only when accessing objects via a pointer or a reference, so you need to change your array to hold Base* pointers:

class Parking {
    static const int MAX_SPOTS_NO = 100;
    Base* B[MAX_SPOTS_NO];
    void parkVehicle() const;
};

void parkVehicle() {
    //call read from the derived class
    ...
    B[index]->read();
    ...
}

Then you can store derived objects in the array as needed, eg 1:

derived *d = new derived;
B[index] = d;

Or:

derived d;
B[index] = &d;

1: You did not provide enough of your code to show you exactly HOW you should best create, manage, and store your derived objects.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770