inheritance - C++ Updating a variable in object of derived class via pointer -
i building linked list, nodes linked head. head derived node, head requires pointer last node. see comment @ top of code.
/* base <= node <= node <= node * | ^ * | ptr last node | * ------------------------- */ class node { private: node* prev; public: explicit node(node* parent) : prev(parent) { node* foo_ptr = this; while (foo_ptr->prev != 0) { foo_ptr = foo_ptr->prev; } // foo_ptr points base, how can change base::last? } }; class base : public node { private: node* last; public: base() : node(0), last(this) {} };
how can change change variable base::last
when adding new node, example:
node* n = new base; new node(n); // can node constructor update n->last?
i thinking use virtual function update variable, according post: calling virtual functions inside constructors, no no not want it. there way of achieving type of linked list?
thanks...
http://coliru.stacked-crooked.com/a/213596aa1ffe7602
i added flag value can tell accessed base
class:
#include <iostream> class node { private: node* prev; public: inline void changebaselast(node* base); explicit node(node* parent) : prev(parent) { node* foo_ptr = this; while (foo_ptr->prev != 0) { foo_ptr = foo_ptr->prev; } // foo_ptr points base // change base::last changebaselast(foo_ptr); } int data; }; class base : public node { private: node* last; public: int flag; base() : node(0), last(this), flag(0) {} }; //here, can see change base_ptr 1. void node::changebaselast(node* base) { base* base_ptr = static_cast<base*>(base); base_ptr->flag=1; } int main() { node* n = new base; new node(n); std::cout << static_cast<base*>(n)->flag << std::endl; }
if pull out part refers derived class , inline it, there should no problems this. notice, though, need define functions refer derived class after define derived class.
if you're sure last node base
object, using static_cast<base*>
may not bad.
Comments
Post a Comment