views:

73

answers:

3

Suppose I have a base and derived class:

class Base
{
    public:
    virtual void Do();
}

class Derived:Base
{
    public:
    virtual void Do();
}

int main()
{
    Derived sth;
    sth.Do(); // calls Derived::Do OK
    sth.Base::Do(); // ERROR; not calls Based::Do 
}

as seen I wish to access Base::Do through Derived. I get a compile error as "class Base in inaccessible" however when I declare Derive as

class Derived: public Base

it works ok.

I have read default inheritance access is public, then why I need to explicitly declare public inheritance here?

+2  A: 

You have read something wrong. The default class inheritance level in C++ is private.

EDIT: I inserted "class" in my answer to match the title of the question and remove any doubt about the context.

Peter G.
`The default inheritance level in C++ is private.` Not necessarily. See the other answers.
Prasoon Saurav
@Prasoon Taken out of context you are right, but the context established by the title and the code clearly is "class" and not "struct".
Peter G.
@Peter G : The downvote isn't mine. Upvoted to counterbalance. :)
Prasoon Saurav
+4  A: 

The default inheritance level (in absence of an access-specifier for a base class )for class in C++ is private. [For struct it is public]

class Derived:Base

Base is privately inherited so you cannot do sth.Base::Do(); inside main() because Base::Do() is private inside Derived

Prasoon Saurav
+3  A: 

From standard docs, 11.2.2

In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.

So, for structs the default is public and for classes, the default is private...

Examples from the standard docs itself,

class D3 : B { / ... / }; // B private by default

struct D6 : B { / ... / }; // B public by default

liaK