Ad

Wednesday, August 01, 2007

Protected Members of a Class

In the previous article Defining Base Class Acess (Inheritance) we noticed that when we derive one class from a base class then no matter which base class access-specifier we use, the members of the derived class doesn’t have access to the private members of the base class.

But what if we want certain members of the base class to be private to the class and at the same time accessible to the members of the derived class? Is there any way of doing it?

Yes, it is possible, by declaring those members as protected members of the base class.

The following example will show you how:


  // ----------------------------
  // -- THIS PROGRAM WON'T RUN --
  // ----------------------------
  // THIS PROGRAM IS DESIGNED TO
  // HAVE ERRORS
  #include<iostream.h>

  // base class
  class base
  {
    int a;

  protected:
    int b;

  public:
    int c;
  };

  // 'derived' class is 
  // inheriting 'base' 
  // publicly
  class derived:public base
  {
    int d;

  public:
    void func()
    {
      cout<<a; //ERROR
      // cannot access private
      // members of the base class

      cout<<b;

      cout<<c;
    }
  };

  void main(void)
  {
    base b;
    derived d;

    d.func();// CORRECT

    cout<<d.b; // ERROR
    // cannot access protected
    // members

    cout<<d.c; //CORRECT
  }

Hence we conclude that protected keyword can be used to declare those members of the class which should be accessible privately to it and at the same time should be accessible to the members of its derived class.

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.