Sign in to follow this  
Quasimodem

C++ Polymorphism Through Pointers to Pointers

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this