Here is the problem — I have two classes like this:
class A
{
//some fields and methods
void niceMethod();
};
class B : public A
{
void niceMethod();
};
class C : public A
{
void niceMethod();
};
and function
void myFunc(A** arrayOfABC);
//Double * is to notice that I am going to modify the argument.
And I want to do:
(*arrayOfABC)[i].niceMethod();
in my function, getting different things done when I pass array of Bs or Cs to function.
But then I try to call it like
B* bees = NULL;
myFunc(&bees);
I have “Argument type of B** is incompatible with parameter of type A**”.
I know that I can pass B or C as A to functions like f(A), but what’s wrong with pointers?
The compiler is right, it is indeed incompatible. Consider this:
Now inside
myFuncyou do this:This should be allowed, because
CextendsA. However, upon return frommyFuncyourbeeswould contain aC, which is not good.To fix this, create an array of
A*, and populate it with pointers toB.P.S. Don’t forget to make
niceMethodvirtual, otherwise it’s not going to work the way you expect.