C++: Leaving open option for a pointer to point to one of two types -


in c++, have 2 classes: node , rootnode. have member node can pointer either node or rootnode. there way can leave open option pointer point 1 of 2 different classes without needing commit 1 of them until set value of pointer?

i have seen answers using union; not sure these work, since use variable defined using union have know whether pointing node or rootnode know object of union reference (union_typedef.node or union_typedef.rootnode). want able use pointer without needing know whether pointing node or rootnode.

there way want do, , way need do (and these 2 different things).

to want (set pointer of 1 of 2 types) use union:

struct mystruct {     union {         node *nodeptr;         rootnode *rootptr;     } }; 

above, can set either nodeptr or rootptr, union take space of single pointer.

what need, however, class inheritance virtual functions, , pointer base class:

struct node {     virtual void dosomething() {         cout << "i'm node" << endl;     } };  struct rootnode : public node {     virtual void dosomething() {         cout << "i'm root" << endl;     } }; 

you can make pointer node, , assign pointer node or rootnode. no matter assign, call of dosomething() routed correct function:

node *n = new node(); n->dosomething(); // prints "i'm node" delete n; n = new rootnode(); n->dosomething(); // prints "i'm root" delete n; 

neither node nor rootnode derive other.

if derivation hierarchy fixed , cannot change it, can build wrapper classes node , rootnode, have 1 wrapper derive other (or have them both derive common ancestor), , make virtual functions dispatch functions of wrapped objects.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -