C++ Polymorphism Through Pointers to Pointers

Started by
3 comments, last by Guthur 15 years, 4 months ago
Hello, I am having difficulty understanding how to get CPP polymorphism working through pointers-to-pointers. Here is the basic problem, let's say I have 2 classes:

class Base { };
class Child : public Base { };

So now I can do cool things like:

Base* base = new Base();
Child* child = new Child();
base = child;

and generally use Child* wherever I could use Base*. Textbook polymorphism, a triumph of civilized man! The problem is, I would also like to be able to use Child** wherever I could use Base**, but my compiler prohibits it. For example, this gives an error "cannot convert from 'Child**' to 'Base**'":

Base** base;
Child** child;
base = child;

Can anyone shed some light onto this situation? Am I doomed to being able to take advantage of polymorphism only at the first level of pointer indirection? I humbly request your aid, GDNet!
Advertisement
Unfortunately, while Child and Base are related types, Child* and Base* are completely unrelated, and you will be unable to convert pointers to Child* and Base* from and to each other.

On a related note, you may think about restructuring your program so that pointers to pointers are not required, and handily avoid this issue. I, personally, have never seen the need for them.

[size=1]Visit my website, rawrrawr.com

Clicky.
Ahoy, it all makes sense now. Thank you both for the lightning-fast replies, this was a tough problem to Google for. Case closed, looks like I get to rethink some code :)
Check out templates if you want some polymorphism :) I have been looking into them recently and they are great, the syntax is a bit unwieldy but they are really quite cool, I made the mistake of avoiding them for too long :) They allow polymorphism alot cleaner than just O-O, imho.
Innovation not reiterationIf at any point I look as if I know what I'm doing don't worry it was probably an accident.

This topic is closed to new replies.

Advertisement