Question

class Base
{
   protected: 
      int data;
   public:
      virtual int getData() { return data; }
      virtual void setData(int value) { data = value; }
};

class Child : protected Base
{
   public:
   void setData(int value)
   {
       Base::setData(value);
       cout << "Data is set.\n";
   }
};

class Worker
{
   private:
      Child obj;
   public:
      void setGlobalData(int val)
      {
         obj.setData(val); // This is normal
      }

      int getGlobalData()
      {
         return obj.getData();  // Line 140, Error
      }
};

Error during compiling of file with Worker class:

Base.hpp: In member function ‘int Worker::getGlobalData()’:
Base.hpp:22:19: error: ‘virtual int Base::getData()’ is inaccessible
Worker.cpp:140:34: error: within this context
Worker.cpp:140:34: error: ‘Base’ is not an accessible base of ‘Child’
Was it helpful?

Solution

Did you actually make it a public base class?

//            vvvvvv important
class Child : public Base

Otherwise it's private, and you get errors similar to what you have, namely:

‘Base’ is not an accessible base of ‘Child’

OTHER TIPS

This compiles:

class Base
{
   protected: 
      int data;
   public:
      virtual int getData() {return data;}
      virtual void setData(int value) { data = value; }
};

class Child : public Base
{
   public:
   void setData(int value)
   {
       Base::setData(value);
       cout << "Data is set.\n";
   }
};

class Worker
{
   private:
      Child obj;
   public:
      void setGlobalData(int val)
      {
         obj.setData(val); // This is normal
      }

      int getGlobalData()
      {
         return obj.getData();
      }
};

Except for clas -> class and virtua -> virtual your code is perfectly fine. There is absolutely nothing wrong with it. Since literally this doesn't compile because of the typos I suspect your original code was a bit different in that the derivation of Child from Base was private or that getData was private.

class Worker not clas Worker

In Worker class, obj.setData(val); is attempting to access a private member of Child class.

Since the current existing version of the code has Child subclassing Base via protected inheritance, the public functions in Base become protected in Child, so Worker can not access them via Child object.

Class Child inherits class Base as protected, so the member function Child::getData() is not publically accessible to clients of Child.

As everyone else here said, changing the inheritance of Base to public is one way to fix it.

class Child: public Base

Also note that casting your Child object to type Base also makes the function Base::getData() of the object publically accessible.

return static_cast<Base *>(&obj)->getData();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top