Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and pointers to pointers: why doesn't it work and how do I get around it?

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?

like image 707
Pierre Avatar asked Feb 03 '26 05:02

Pierre


1 Answers

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.

like image 140
TomW Avatar answered Feb 05 '26 18:02

TomW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!