1

I'm trying to experiments with inheritance in c++. I've written the following code:

#include <stdio.h>

class A
{
public:
    virtual void foo();
};

class B: A
{
    void foo();
};

void B::foo()
{
    printf("Derived class");
}

void A::foo()
{
    printf("Base class");
}

int main()
{
    A *a= new B();
    a->foo();
}

But I've an error described as

test.cpp: In function ‘int main()’: test.cpp:26:14: error: ‘A’ is an inaccessible base of ‘B’

It works fine if I replace the line class B: A to class B: public A. But using this fact I really don't understand in what case private and protected inheritance may be needed. It's useless for me now.

  • `public` inheritance introduces an IS-A relationship visible and usable by other code. `protected` inheritance limits that relationship visibility to derived classes. `private` inheritance limits to this class only. This helps to avoid that client code becomes tied to an implementation detail. However, `private` inheritance is a special case because the virtual member functions inherited from the base class are still virtual in (and can be overridden in) derived classes, just not accessible for calling. – Cheers and hth. - Alf May 05 '14 at 04:12
  • Another SO post on the subject: http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance-in-c?lq=1 – R Sahu May 05 '14 at 04:18

1 Answers1

0

You are accessing B::foo() using A*. But both the inherited A::foo() and overridden B::foo() are private.

About inheritance concept:

public : derived class IS-A base class private/protected: derived class has a base class \ derived class is implemented-in-terms of base class.

Inherit publicly when derived object is replaceable to base object. Inherit privately when derived class only needs the implementation of base class (not interface). But in the later case Composition is preferred approach than inheritance.

check this and this

Rakib
  • 7,435
  • 7
  • 29
  • 45