inheritance

T

tolkien

Hi!!!
I Have this:
#include<iostream.h>

class base
{
protected :
int b;
};

class derived: public base
{
private :
int d;
public:
int xxx(base k) //int xxx(derived k) works with derived
{
return b + k.b; //cannot access k.b,

}
};



Why Can't i access member b of the variable k if k is of type base?
It works fine is k is of type derived!!!

I can access b ,why can't i access k.b ??
b is protected therefore i can access it inside the derived class with
the "." operator,no?
 
T

tolkien

I assume that the derived class has access only to its inherited
protected members .
If it needs access to member b of another base object must call a
getB() function,right?
 
G

gw7rib

Hi!!!
I Have this:
#include<iostream.h>

class base
{
   protected :
           int b;

};

class derived: public base
{
   private :
           int d;
   public:
            int xxx(base k)   //int xxx(derived k) works with derived
           {
                   return b + k.b;  //cannot access k.b,

           }

};

Why Can't i access member b of the variable k if k is of type base?
It works fine is k is of type derived!!!

I can access b ,why can't i access k.b ??
b is protected therefore i can access it inside the derived class with
the "." operator,no?

I asked much the same question back in March. Apparently, the reason
xxx(derived k) works is beacause a class is automatically a friend of
itself, and so the derived can access the members of the other derived
k. However, derived is not a friend of base, and so xxx(base k) cannot
access the members of k. Strange but (apparently) true.

Hope that helps.
Paul.
 
P

puzzlecracker

I asked much the same question back in March. Apparently, the reason
xxx(derived k) works is beacause a class is automatically a friend of
itself, and so the derived can access the members of the other derived
k. However, derived is not a friend of base, and so xxx(base k) cannot
access the members of k. Strange but (apparently) true.

Hope that helps.
Paul.

I've have never encountered this problem, but then, I always use
accessor functions, especially in the context of derived classes.

Is this part of standard? To my knowledge, this should be allowed, and
the error is the issue with compiler, and not the programmer.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top