Why this code is not working?

Discussion in 'C' started by imrantechi, May 4, 2009.

  1. imrantechi

    imrantechi New Member

    Joined:
    Feb 12, 2008
    Messages:
    116
    Likes Received:
    4
    Trophy Points:
    0
    CASE 1: Following code is not working...saying
    error: `int Base::j' is protected
    error: within this context


    Code:
    #include<iostream.h>
    
    class Base
    {
    public:
      Base() { i=10; j=20;}
      int i;
    protected:
      int j;
    };
    
    class Derived : public Base
    {
    public:
      Derived() { k=30;}
      int k;
    void fun(Base);
    };
    
    void Derived :: fun(Base b)
    {
      b.i=100;
      b.j=200;   //Problem is here...
    }
    
    int main()
    {
      Base Bobj;
      Derived Dobj;
      Dobj.fun(Bobj);
          
      return 0;
    }

    CASE 2: This code works fine...This is reasonable...
    Code:
    #include<iostream.h>
    
    class Base
    {
    public:
      Base() { i=10; j=20;}
      int i;
    protected:
      int j;
    };
    
    class Derived : public Base
    {
    public:
      Derived() { k=30;}
      int k;
    void fun(Base);
    };
    
    void Derived :: fun(Base b)
    {
      b.i=100;
      this->j =200;
      //b.j=200;
    }
    
    int main()
    {
      Base Bobj;
      Derived Dobj;
      Dobj.fun(Bobj);
          
      return 0;
    }
    But in case 1, i think compilation error should not come, because protected member is accesing by derived function only.
     
  2. sharmila

    sharmila New Member

    Joined:
    Mar 24, 2006
    Messages:
    75
    Likes Received:
    1
    Trophy Points:
    0
    In base calss j is protected member. In case 1 you are trying to assign value for a protected member . so it failed.
    Where as in case 2, you used 'this' means derived class object. When a derived class object is created internally it will create base class object too . Since j is protected it is accessible by the derived class..
    So you can assign the value. Where as in case 1 Base b is a different object, so you can't access the protected variable.
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice