Why do I get a compilation error when I call a base-class function with a pointer to a pointer to an inherited class?
Example:
class cFoo {};
class cBar : public cFoo {};
void func1(cFoo *) {} // base class
void func2(cFoo **) {} // base class
void main(void)
{ cBar bar, *pbar; // inherited class
func1(&bar); // compiles OK
func2(&pbar); // fail
func2(dynamic_cast<cFoo**>(&pbar)); // 'class cFoo ** ' : invalid target type for dynamic_cast
}
How do I get around this?
Consider the following:
class cFoo {};
class cBar : public cFoo {};
void func1(cFoo *) {}
void func2(cFoo **p) { *p = new cFoo; } // modify pointee
void main(void)
{ cBar bar, *pbar; // inherited class
func1(&bar); // compiles OK
func2(&pbar);
}
If that worked, you would have managed to put a cFoo object into a cBar pointer with no compiler error, and the type system would be subverted. A dynamic cast would not help, since there is no way the cast could prevent the damage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With