How to make methods from parent class use a different variable?

99 views Asked by At

I have a class like this:

class A {
protected:
    class Node {
    public:
        int x;
        Node* next;
    };

    Node* root;
    .
    .
    .
};

And a lot of methods using this "root".

Now, say I want to inherit from A class, and make all the methods use a "better" node. Something like:

class B : public A{
    class NewNode : public A::Node{
    public:
        int y;
    };

    NewNode* root;
    .
    .
    .
};

Is there a way of doing something like this? And if not, what are the alternatives (beside rewriting A class)?

Thank you!

2

There are 2 answers

1
IronMensan On BEST ANSWER

Since NewNode is derived from Node you can put something like this in the B constructor

delete root;  //remove the Node
root = new NewNode();  //and put in the better one

More realistically, you'll probably need something like this

Node * oldRoot = root;
root = new NewNode(oldRoot);
delete oldRoot;

You don't need a new variable in B, just use A::root.

0
JonathanK On

If A is abstract, it can be compiled and used with all its methods independently from any derived classes. Therefore, code that accesses this variable will already be generated and cannot change. I think there is really no way to do what you want to do, without modifying A.

Although, it depends a little bit, what exactly you mean. If NewNode is derived from Node and Node has virtual functions, A will of course call the methods of NewNode. If you don't want NewNode to be derived from Node, you probably have to make A a template class. This would also work, if A accesses members of Node directly, instead of using virtual Getter/Setter-Functions.