-5
#include <iostream>
using namespace std;
class B
{
  public:
  int x;
  void print()
  {
    cout<<x;
  }
};

class D:private B
{
};

int main()
{
  D d;
  d.print();
}

Why can't I access print method ? Print method from B will be private property of D so it's logical that I should access it using object of D. The error I'm getting is this:

'B' is not an accessible base of 'D'.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
AlokI
  • 1
  • 3

1 Answers1

2

Private inheritance means that the base class is accessible only within the member functions of the derived class. In general you use private inheritance when you want to model a has-a relationship, not a is-it. It's not the case here, you are trying to directly call it in main(). This will work instead:

#include <iostream>

class B
{
public:
    int x{42};
    void print()
    {
        std::cout << x;
    }
};

class D: private B
{
public:
    void f()
    {
        print(); // can access the private one in B
    }
};

int main()
{
    D d;
    d.f();
}

Live on Coliru

You can read about it more here: Difference between private, public, and protected inheritance

Or, as @WhozCraig mentioned, you can change the access via a using statement in the public section of your derived class:

using B::print; // now it is visible in the derived class
Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Or you could use `protected`. – Jesper Juhl Sep 13 '16 at 19:10
  • @JesperJuhl Hmm, imho `protected` inheritance should just be disallowed, it makes (complicated) things too complicated. I don't think anyone can come up with a killer example where `protected` inheritance is needed. Do you have one? – vsoftco Sep 13 '16 at 19:13
  • @vsoftco I tend to agree with you, but OP *could* solve his problem by making the member in the base class `protected` rather than private and then using public or protected inheritance to achieve his desired result (as I read it) of not allowing outside access but still having 'in-class' access in the derived class. I was going for a `protected:` member, not arguing specifically for 'protected inheritance' (which I agree is "icky" and not too useful). – Jesper Juhl Sep 13 '16 at 19:24