C++ Class Inheritance with protected members

Introduction

The following example introduces the new access specifier called protected:

The derived class itself can access protected members of a base class.

The protected access specifier allows access to the base class and derived class, but not to objects:

class MyBaseClass 
{ 
protected: /*w w w .j  av  a  2 s . c o m*/
    char c; 
    int x; 
}; 
class MyDerivedClass : public MyBaseClass 
{ 
    // c and x also accessible here 
}; 

int main() 
{ 
    MyDerivedClass o; 
    o.c = 'a';    // Error, not accessible to object 
    o.x = 123;    // error, not accessible to object 
} 



PreviousNext

Related