user1416583
user1416583

Reputation: 5

C++ class inheritance and member functions

All, I am having difficulty understanding why I am getting the following error. I promise this is not a homework problem, but I am new to C++! Here is my code:

#include <iostream>
#include <string>
#include <vector>

class Base {
protected:
  std::string label;
public:
  Base(std::string _label) : label(_label) { }
  std::string get_label() { return label; }
};

class Derived : private Base {
private:
  std::string fancylabel;
public:
  Derived(std::string _label, std::string _fancylabel)
   : Base{_label}, fancylabel{_fancylabel} { }
  std::string get_fancylabel() { return fancylabel; }
};

class VecDerived {
private:
  std::vector<Derived> vec_derived;
public:
  VecDerived(int n)
  {
    vec_derived = {};
    for (int i = 0; i < n; ++i) {
      Derived newDerived(std::to_string(i), std::to_string(2*i));
      vec_derived.push_back(newDerived);
    }
  }
  std::string get_label(int n)  { return vec_derived.at(n).get_label(); }
  std::string get_fancylabel(int n) { return vec_derived.at(n).get_fancylabel(); }
};

int main (void)
{
  VecDerived obj(5);
  std::cout << obj.get_label(2) << " " << obj.get_fancylabel(2) << "\n";
  return 0;
}

The compiler error I get is as follows:

test1.cpp: In member function ‘std::__cxx11::string VecDerived::get_label(int)’:
test1.cpp:33:70: error: ‘std::__cxx11::string Base::get_label()’ is inaccessible within this context
   std::string get_label(int n)  { return vec_derived.at(n).get_label(); }
                                                                  ^
test1.cpp:9:15: note: declared here
   std::string get_label() { return label; }
               ^~~~~~~~~
test1.cpp:33:70: error: ‘Base’ is not an accessible base of ‘__gnu_cxx::__alloc_traits<std::allocator<Derived> >::value_type {aka Derived}’
   std::string get_label(int n)  { return vec_derived.at(n).get_label(); }

I don't understand why the member function get_label() wasn't inherited from the Base class to the Derived class, such that I'm not able to access it via the VecDerived class. Is there a way that this can be resolved? Thanks in advance for your help!

Upvotes: 0

Views: 71

Answers (1)

Werner Henze
Werner Henze

Reputation: 16726

Visual Studio emits an error message that gives you more hints:

error C2247: 'Base::get_label' not accessible because 'Derived' uses 'private' to inherit from 'Base'

So if you want to access Base::get_label through a Derived object, then you either need to make the base class public:

class Derived : public Base

or make get_label public:

class Derived : private Base {
public:
    using Base::get_label;

Upvotes: 1

Related Questions