You are on page 1of 14

The Protected Keyword

 A derived class does not have access to the


private members of the base class.
 However, when you want to keep a member
of a base class private but still allow a derived
class access to it.
 To accomplish this, C++ includes the protected
access specifier.
 Access is denied to everyone else.

1
Inherited Access
 Access depends on the kind of inheritance;
public, protected or private – that is specified
in the definition of the derived class.

2
Inherited Access
Public Inheritance
 Public inheritance means that:
– public members of the base class become public
members of the derived class;
– protected members of the base class become
protected members of the derived class;
– private members of the base class become
inaccessible within the derived class.

3
Inherited Access
Protected Inheritance
 Protected inheritance means that:
– public members of the base class become
protected members of the derived class;
– protected members of the base class become
protected members of the derived class;
– private members of the base class become
inaccessible within the derived class.

4
Inherited Access
Private Inheritance
 Private inheritance means that:
– public members of the base class become
private members of the derived class;
– protected members of the base class become
private members of the derived class;
– private members of the base class become
inaccessible within the derived class.

5
Inherited Access
Summary

Inheritance and Accessibility

6
Inherited Access
Example (Public Inheritance)
class Base class DerivedClass : public Base
{ {
public: void test() {
int m1; m1 = 1; // public is still public
protected:
m2 = 2; // protected is still protected
int m2;
m3 = 3; // private:error, not accessible
private:
}
int m3;
};
};
7
Inherited Access
Example (Protected Inheritance)
class Base class DerivedClass : protected Base
{ {
public: void test() {
int m1; m1 = 1; // was public, now protected
protected:
m2 = 2; // protected is still protected
int m2;
m3 = 3; // private:error, not accessible
private:
}
int m3;
};
};
8
Inherited Access
Example (Private Inheritance)
class Base class DerivedClass : private Base
{ {
public: void test() {
int m1; m1 = 1; // was public, now private
protected:
m2 = 2; // was protected, now private
int m2;
m3 = 3; // private:error, not accessible
private:
}
int m3;
};
};
9
Example 1

10
Drive Class

11
Example 2

12

You might also like