Inheritance public vs nothing ?

Hi
i was wondering whats the difference between this:

1
2
3
class child : public parent
{
};


and this:

1
2
3
class child : parent
{
};


?
If parent is a struct, it's like this:

1
2
3
class child : public parent
{
};


If parent is a class, it's like this:

1
2
3
class child : private parent
{
};
No, what matters is if child is a class or a struct.

Since child is a class it will use private inheritance by default. From outside the child class it's as-if it doesn't inherit from parent at all. You can't access public members of parent, and you can't use parent pointers or references to point to child objects. From inside the child class you can still do all the things you could do with public inheritance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class parent
{
public:
	void f();
};

class child : private parent
{
	void g()
	{
		f(); // OK
		parent* p = this; // OK
	}
};

int main()
{
	child c;
	c.f(); // Error 
	parent* p = &c; // Error
}
Last edited on
Oh yes, what he said. Child, not parent. I don't think I've ever not explicitly stated the inheritance.
Topic archived. No new replies allowed.