0

I am trying to implement an AVL tree. Initially I implemented two classes, node and node_AVL as such:

class node{
protected:
    int info;
    node *l, *r;
public:
    node *getRight();
};

class node_AVL : public node{
protected:
    int height;
public:
    void setHeight(int):
};

The problem arises when for example I try to access the child of a node:

node_AVL *node1 = node2.getRight();

Or

node_AVL node;
node.getRight().setHeight(1);

I get these errors:

Invalid conversion from node* to node_AVL*

Class node has no member setHeight()

How can I solve this?

  • 3
    What do you mean "problem arises"? Do you get a compiler error? – cigien Apr 24 '20 at 17:32
  • 2
    Please make a [MRE] for example what is `getRight`? Assuming `getRight` returns a `node*` the line `node_AVL node1 = node2.getRight();` can't work, because 1.) you try to assign a pointer to a non-pointer-variable and 2.) you can't assign a `node *` to a `node_AVL *`, because a `node *` is not necessarily a `node_AVL *`. – Lukas-T Apr 24 '20 at 17:37
  • 2
    `node2.getRight()` presumably returns a `node*`, which may or may not point at a `node_AVL*`, so you're not allowed to call those methods. – Mooing Duck Apr 24 '20 at 17:38
  • I think I get it now, but is there a way to create a class that inherits node but adds new data, like height in my example? – Andrei Mihailescu Apr 24 '20 at 17:42
  • 1
    Your example does exactly that, it creates "a class that inherits node but adds new data". That happens to be exactly what it does. – Sam Varshavchik Apr 24 '20 at 17:43
  • 1
    You've run into what the [Liskov Substitution Principle](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle) warns of. You have a hierarchy that makes sense on the surface, but doesn't make sense the way you need to use it. – user4581301 Apr 24 '20 at 17:44
  • Note: your `node` needs to have a public virtual destructor if its subclasses can ever be deleted through a `node` pointer. Otherwise, all their fields leak on `~node()` call , e.g. node_AVL::height (it probably can even cause undefined behavior). If objects of derived classes mustn't be deleted through a pointer to the superclass, you can explicitly forbid it by making `~node()` protected. – passing_through Apr 24 '20 at 18:52

1 Answers1

0

As the error messages say, this line:

node_AVL *node1 = node2.getRight();

doesn't work because getRight() returns a node*. You could fix this by making node1 a node*, like this:

node *node1 = node2.getRight();

For the second part, you would need to do something like:

node node;
node.getRight()->setHeight(1);

This wouldn't work either since setHeight is a member of node_AVL.

You should maybe redesign your class, bearing in mind what you're trying to accomplish.

cigien
  • 57,834
  • 11
  • 73
  • 112