简体   繁体   中英

Accessing derived class from base class pointer with a fixed array size

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
}

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM