Public vs private inheritance?

Mar 7, 2012 at 8:05pm
In my comp sci class today, we learned that C++ allows the inheritance itself to have a visibility. What does that mean? I don't really understand the concept....How is public inheritance different from private inheritance?
Mar 7, 2012 at 8:11pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Class1
{
    void DoStuff(){} //this is public
protected:
    void DoThing(){} //this is protected
private:
    void DoAnother(){} //this is private
};
struct Class2 : Class1 //public inheritance
{};
class Class3 : Class1 //private inheritance
{};
struct Class4 : protected Class1 //protected inheritence
{};

Class1::DoStuff is public
Class1::DoThing is protected
Class1::DoAnother is private to Class1

Class2::DoStuff is public
Class2::DoThing is protected
Class2::DoAnother is private to Class1

Class3::DoStuff is private to Class3
Class3::DoThing is private to Class3
Class3::DoAnother is private to Class1

Class4::DoStuff is protected
Class4::DoThing is protected
Class4::DoAnother is private to Class1

Note that, just as Class4 specified protected, you can also specify public and private. You do not have to specifically use class or struct, they just have those defaults.
Last edited on Mar 7, 2012 at 10:06pm
Mar 7, 2012 at 9:19pm
Class4::DoStuff is protected
Class4::DoThing is protected
Class4::DoAnother is private to Class1

Class4::Crashes due to the typo when specifying the inheritance ;-)

Tee hee. Couldn't resist that one.

On a serious note, in addition to L B's example, you can also publicly inherit to a class or privately inherit to a struct by using the public/private keywords when inheriting.
Mar 8, 2012 at 4:34am
What does that mean?


public inheritance is the "is-a" relationship. A Derived object is a Base object. The public interface is inherited.

private inheritance is the "implemented-in-terms-of" relationship. A Derived object is not a Base object, but is built on top of one Base object, internally. This is very closely related to the more common "has-a" relationship.
Topic archived. No new replies allowed.