Sorry if this answer is already on this site, but I've looked all over and couldn't find any solutions to my issue. It pertains to same-name functions from inherited classes. Here is my code:
class A
{
public:
int foo(int c) { c = c+1; return c; };
};
class B : public A
{
public:
int foo(int c) { c = c-1; return c; };
};
int main()
{
A array[2];
array[0] = A item1;
array[1] = B item2;
for (int n=0;n<2;n++)
{
cout << array[n].foo(10) << endl;
}
return 0;
}
I would expect an output of:
11 // foo() from A class [10 + 1 = 11]
9 // foo() from B class [10 - 1 = 9 ]
But instead I get
11
11
From testing this out, I have found that the foo() function in the B class does not get called within the for-loop. Instead, the foo() function in the A class is called, even on the B object at array[1].
Is this because I have defined the array as containing objects of the A class only? If so, is there a way I can have the foo() function from the B class be called on the second object within that for-loop?
Thank you in advance for any help!