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!
I’ll forget that
array[0] = A item1;isn’t valid C++ and just assume that you’re assigning an object of typeAtoarray[0]and an object of typeBtoarray[1]. Okay, so you have two problems.The first is known as object slicing. When you copy an object of type
Bto an object of typeA, you only copy theApart of that object. So what you have inarray[1]is not aBat all, it’s just anA. If you want polymorphism (which you do), then you need to use either pointers or references which provide polymorphic behaviour. That means make your array anA* array[2];and doarray[0] = &item1; array[1] = &item2;.Now, when you call a function on a pointer to
Athat points to aBit will still only callAsfoomember function. Why? Because by default, the function will be looked up on the static type of the object. That static type isA. If you want to tell the compiler to look up your function on the dynamic type of your object – the true type of your object, which isB– you need to make that member function virtual. So inA, do:Now when your compiler see that you’re calling
fooon anA*, it’ll see that it’s virtual and say “Oh okay, I should look up this function dynamically” and it’ll findB‘s implementation offoo.