V
V
Vladimir Petrigo2015-02-19 00:35:42
Programming
Vladimir Petrigo, 2015-02-19 00:35:42

Is it possible to use protected class constructors in an inheritor?

Good afternoon.
I am reading Stroustrup's book and there, using the example of working with the FLTK graphics library, methods of inheritance are explained. I got to one moment, the approximate code of which is given below:

class A {
protected:
  A();
  A(initializer_list<int> lst) {
    for (auto a : lst)
      add(a);
  };
  
  void add(int a) {
    vals.push_back(a);
  }
public:	
  ~A() {};
  
  void get_vals(void) const {
    for (auto i : vals)
      cout << i << '\n';
  }
private:
  vector<int> vals;
};

struct B : A {
  using A::A;
};

The book says that using such inheritance, you can use the initializing list in your code when creating an element of class B: But attempts to reproduce this situation lead to the expected result: g++-4.9.2
B elem{1, 2, 3, 4};

error: 'B::B(std::initializer_list<int>)' is protected

VC++13
IntelliSense: no instance of constructor "B::B" matches the argument list argument types are: (int, int, int, int) ProtectedTest

Remembering about inheritance types, I did not understand how you can use protected members or methods of a derived class outside of yourself. I turned to the standard and there, in section 12.9/4, it is written that using the using X::X construct, access modifiers in the derived class remain the same as in class X.
Please explain whether I am right or if I do not catch some moment.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Petrigo, 2015-02-19
@vpetrigo

Apparently, this error can be corrected only by explicitly declaring the necessary constructor in the inherited class, using the base constructor:

struct B : A {
  B(initializer_list<int> lst) : A{lst} {}
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question