1

I want to do classes which inherit from the same base class. And to be easier to use, I want to store class instances in an array and call method provide by the base class and override in subclasses.

But, it doesn't work like I think.

An example of code to illustrate :

class A
{
public:
    A() {}
    ~A() {}

    virtual void F()
    {
        std::cout << "Hello A !" << std::endl;
    }
private:

};

class B : public A
{
public:
    B() {}
    ~B() {}

    virtual void F() override
    {
        std::cout << "Hello B !" << std::endl;
    }
private:

};

int main()
{
    A aArray[2];
    A a;
    B b;

    aArray[0] = a;
    aArray[1] = b;

    std::cout << "Direct call to F" << std::endl;
    a.F();
    b.F();

    std::cout << "Call to F by array" << std::endl;
    aArray[0].F();
    aArray[1].F();

    system("pause");

    return 0;
}

And I get as result :

Direct call to F
Hello A !
Hello B !
Call to F by array
Hello A !
Hello A !

My goal is to find a way when I write : "aArray[1].F();" which is an instance of the class B to call the method from the class B and not the method from the class A.

How to do that ? Thx a lot.

Shadleur

Shadleur
  • 13
  • 2

0 Answers0