简体   繁体   中英

How to manage base-class instances and derived-class instances in one vector?

The Problem:

I have a class, lets say, mainClass . Now I create two other classes and let them inherit from the base class.

So, I want to manage all instances of any either base or inherited class and store them in, for example, a vector (doesn't have to be a vector, if it doesn't work).

std::vector<mainClass*> indeed accepts all instances of inherited classes but I can't acess those functions who are new declared in the inherited class, only those who are also member of the base class..

Is there any way, maybe with templates, to solve this? Or do I overlook something simple?

The purpose of inheritance is to allow to call the methods of the derived classes through the base class. To do this, the base class defines the methods as virtual . If you define all the methods you need to call in the derived classes as virtual in the base class, you can call them through your mainClass* .

If you don't do this, you would have to know which instance is of which class, and cast accordingliy.

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