Page 1 of 1

case study: why to use 'protected' inheritance

Posted: Fri Apr 19, 2013 6:14 am
by SemiconductorCat
Hi all, Today I'm going to write about why we need to use 'protected' inheritance. Before going straight into
'protected' inheritance I'll discuss why we need a access modifier related to the inheritance.

The basic idea of using a access modifier to inheritance

You may seen something like that.

Code: Select all

class MyDerivedClass: private MyBaseClass{ // continue 
It simply saying that class 'MyDerivedClass' does inherit attributes and behaviors from it's base class 'MyBaseClass'
but it don't like to show outside that it derived from 'MyBaseClass' at all. Analogy is for a example , some people
don't like to show that they derived from their family [due to bad social reputation or something],but they don't
hesitate to use all the properties and asserts derived to them from their family.

On the 'protected' inheritance only your children will be allowed to know about their relationship with grandfather's
family. But suppose they were advised to keep that in secret too.And only to pass that information to their
children only.


On 'public' inheritance, it's like your family have well reputation , so there's nothing to be hided about your
family inheritance.


You could find lots of examples to private and public inheritance in Object Oriented Programming world as well.
But the cases which involve 'protected' inheritance are very rare. So I'm going to explain you a case study where
you need 'protected' inheritance.

Case Study


Implement a wrapper top of the old class library. The class user (client programmer) should not be able to use
the functions/attributes of the old class library interface. But if client asks explicitly to return old class library
object it should allow if reasons are fair.

Typical Code Implementation .

Code: Select all


// old library //
class OldLibrary{
public:
  void methodA();
  void methodB();

};

// New Library //
class NewLibrary: protected  OldLibrary{
public:
  void NewMethodA(){
    OldLIbrary::methodA();

  }

  void NewMethodB(){
    OldLibrary::methodB();
  }
  
  OldLibrary& GetOldLibrary(){
   return *this;
 }
  
};
Where in the code NewLibrary::GetOldLibrary() , it used the concept that 'NewLibrary' have been derived from
'OldLibrary" otherwise (*this) could not be uppercased to the OldLibrary at all.


Hope you understand the concept.

--Thanks for Reading--