Question about inheritance

I have a base class called Node. Inside the class I have a data member that is a vector to keep track of children. I want to make a derived class called LeafNode. I don't want the leaf node to inherit the vector. How do I stop it?

1
2
3
4
5
6
class Node
{
...
private:
	vector <Node*> myChildren; // I don't want my derived class LeafNode to inherit this
};
Last edited on
It will not inherit that member. As that member is private.
Oh I see. Another question would be is it always a good practice to make every data member private or have some public to be inherited or is that bad?
Errr....

It does inherit private stuff. It just can't access it. However it could still be accessed by public/protected member functions of the parent class.

You cannot prevent a child class from inheriting some stuff from its parents -- it's all or nothing. If you don't want a class to have some information you need to design your hierarchy differently. Perhaps derive them both from an abstract base:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class NodeBase
{
public:
  // stuff for all types of nodes
};

class Node : public NodeBase
{
private:
  vector<NodeBase*> myChildren;
};

class LeafNode : public NodeBase
{
 // class can have all the same member functions that NodeBase has, but
 // will not have the vector that Node has
};


I usually go protected for most things that aren't public in my classes, simply because I may choose to derive another class from it which does something similar in the future. I use 'private' mostly for classes which I know will have children, and I want some stuff intentionally hidden from them. I can't really come up with good specific examples.

Anyway if you aren't planning on having any children for a class -- choosing between private/protected isn't really all that important IMO.
Last edited on
Topic archived. No new replies allowed.