C ++ can not instantiate a subclass because of a parent protected constructor?

advertisements

This is the code i have trouble understanding:

class A
{
protected:
   int _i;
   A () : _i(0) { }
   ~A () { }
}; 

class B: public A
{
public:
   A *_pa;
   B()  : A(), _pa(new A())
   { } 

  ~B ()
   {
      delete _pa;
   }
}; 

int main ()
{
   A a; //ERROR
   B b; //ERROR
}

When trying to instantiate a class of type A i get an error because it's constructor is protected. But why can't I instantiate a class of type B? The class has access to protected members of A (including the ctor) so it should compile.


Your error is located the new A inside the B constructor, not on the call to super's constructor.

Let me explain you how protected works. When you have a class B, which is subclass of A it does not have access to protected elements of A, it has access to protected elements of A when dealing with a B reference.

To show my point:

#include <iostream>

class A {
protected:
    int a;
};

class B : public A {
public:
    void do_it(A* a) {
        std::cout << a->a << std::endl; //ERROR
    }
    void do_it(B* a) {
        std::cout << a->a << std::endl; //VALID CODE
    }
};

I guess the reason behind this behavior is that if you have a third class C which also access A protected members, probably it is not a good idea that someone else change these protected values.