0
class A{
fct1(){}; 
};

class B:public A{
fct2(){};  
};
// B b; 
// A* a = &b; good! possible!!

class A{
fct1(){}; 
};
class B:protected A{
fct2(){};  
};
//B b;
// A* a=&b; error!

why is that?

What does protected inheritance have to do with pointer?

I learned that protected inheritance changes public area to protected area, so that only derived class can access its member functions and variables. :(

Please explain the principle and reason.

0

1 Answer 1

0

The whole point of access control is to ... control who gets access to which parts of a class. "Protected" means that only derived classes have access.

The access level on a base class determines access to the base subobject. Putting this together, this means that only derived classes have access to protected base subobjects. So the conversion of &b to a pointer to A is not allowed outside classes derived from A.

3
  • Then I can't build polymorphism with protected inheritance? May 21, 2016 at 13:51
  • and does subobject mean something like fct1 in class? I learned C++ in Korean :P May 21, 2016 at 13:53
  • "Polymorphism" is a dangerously vague word. Usually, "dynamic polymorphism" (or "virtual-function polymorphism") refers to public inheritance. In that interpretation of polymorphism, you want to treat a B as if it was an A, so the base subobject must be public.
    – Kerrek SB
    May 21, 2016 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.