简体   繁体   中英

How do I create an array of inherited class objects?

I'm having a bit of trouble working on my current project. The project consists of taking lines of data from a file and creating an array of class objects that all inherit a base class.

So, this is what I understand so far:

class BaseClass {
    // create empty and non-empty constructor
}

class SubClass : public BaseClass {
    // create constructor specifically for this class 
}

int main() {
    BaseClass *array[size];
    array[index] = new SubClass();

    return 0;
}

Since the SubClass inherits the BaseClass, When I add a new object to the array it should be of type SubClass, correct?

When I debug the program and look at that object, it doesn't allow me to point to any of the SubClass methods/variables for manipulation which is what I need to be able to do.

Now when I was searching for answers I came across static casting, so I tried it to the extent of:

(static_cast<SubClass*>(array[index])->subclass_variable) = some_value

But that doesn't seem to work either, any help with this would be greatly appreciated.

One way to handle this is defining an interface (virtual methods) in the base class and implementation in SubClass :

class BaseClass {
    // create empty and non-empty constructor
    virtual void f() = 0;
}

class SubClass : public BaseClass {
    // create constructor specifically for this class 
    virtual void f() { std::cout << "I am your SubClass" << std::endl; }
}

Then you can call array[index]->f(); .

Another way is visiting / type switching on the class, another is NVI, but those are somewhat more advanced topics.

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