2

Am a newbie to C++.

class A 
{
    public:
        int i;
    protected: //**--- [1]**
        void set()
        {
            i=5;
            cout<<i;
        }
};

class B : public A
{
    public:
        void call()
        {
            A obj;
            obj.set(); //**----[2]**
            set(); //**---[3]**
        }
};

int main()
{
    B* b_obj = new B;
    b_obj->call();
}

Why doesn't the code compiled if i try including [2] and not replacing [1] to public BUT it works if i compile including [3] alone?

Compiled error: error: ‘void A::set()’ is protected.

In short, My intention is to understand why base object cannot be called in derived class if the access specifier for the base class interface is set as protected.

Richard D
  • 327
  • 3
  • 16
Xpeditor
  • 7
  • 1
  • 4

2 Answers2

2

Not sure if my answer is correct, but here goes:

set is protected in class A. This means no outside member can access set, but derived classes can.

When calling set() by itself inside B you are calling the function as a derived function from A inside your derived class B, meaning the compiler will accept this because the function is protected (accessible to derived classes.)

However when you define A obj, calling obj.set(), in relation to the obj instance, the call is external to the class, hence why the compiler gives error.

Hope that helps.

Joel
  • 385
  • 1
  • 3
  • 15
1

Pet is unrelated to A or B, so whether f.set() is allowed depends on the definition of Pet. By contrast, just set() works because it's protected in the base class, and hence accessible in derived classes.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084