Search code examples
c++visual-studioclasspointersabstract-class

Is It possible to call methods from a subclass from a base class type?


Hello everyone and thanks for reading, I'm new to working with classes and I've ran into an issues with making array's of objects, I have a base class, and an array of the same type, I'd like to know if it's a possibility to make subclasses of the base class type and put them into an array and call methods that're not in the base class, sorry if this is a bad question and my apologies if my wording is off,

#include <iostream>

int main()
{
    BaseClass* ObjectList[10];
    ObjectList[0] = new SubClass;
    ObjectList[0]->Load(10);
    ObjectList[0]->OtherFunction();     // How Can I Do This?
    return 0;
}


class BaseClass
{
public:
    virtual void Load(int Num) = 0;
};


class SubClass : public BaseClass
{
    void Load(int Num) override
    {
        std::cout << Num << std::flush;
    }
    void OtherFunction()
    {
        // Do Something
    }
};

Thanks

Edit - My intent is to have a simple base class with dozens and dozens of subclasses with different methods, and have an array of the base class,


Solution

  • You can always have more than one pointer (or reference) to the same object.

    int main()
    {
        BaseClass* ObjectList[10];
        SubClass TheSubclass;
        ObjectList[0] = &TheSubclass;
        ObjectList[0]->Load(10); // presumably in a loop
        TheSubclass.OtherFunction();
        return 0;
    }