Search code examples
c++memberprotectedsuperclass

Why protected superclass member cannot be accessed in a subclass function when passed as an argument?


I get a compile error, which I'm slightly confused about. This is on VS2003.

error C2248: 'A::y' : cannot access protected member declared in class 'A'

class A
{
public:
  A() : x(0), y(0) {}
protected:
  int x;
  int y;
};

class B : public A
{
public:
  B() : A(), z(0) {}
  B(const A& item) : A(), z(1) { x = item.y;}
private:
  int z;
};

The problem is with x = item.y;

The access is specified as protected. Why doesn't the constructor of class B have access to A::y?


Solution

  • It's because of this:

    class base_class
    {
    protected:
        virtual void foo() { std::cout << "base::foo()" << std::endl; }
    };
    
    class A : public base_class
    {
    protected:
        virtual void foo() { std::cout << "A::foo()" << std::endl; }
    };
    
    class B : public base_class
    {
    protected:
        virtual void foo() { std::cout << "B::foo()" << std::endl; }
    
    public:
        void bar(base_class *b) { b->foo(); }
    };
    

    If that were legal, you could do this:

    A a;
    B b;
    b.bar(&a);
    

    And you'd be calling a protected member of A from B, which isn't allowed.