about base class's protected member

Z

Zealot

class Base
{
protected:
int var;
};

class ChildB : public Base
{};

class ChildA : public Base
{
void foo( ChildB* B )
{
var = B->var; C2248..
}
};

why I can not process ChildB's member var ??
 
J

John Harrison

Zealot said:
class Base
{
protected:
int var;
};

class ChildB : public Base
{};

class ChildA : public Base
{
void foo( ChildB* B )
{
var = B->var; C2248..
}
};

why I can not process ChildB's member var ??

Because ChildB is not derived from ChildA. Access to protected members from
a derived class must be made through a pointer to, reference to, or object
of the derived class itself (or any class derived from that class).

Using your previous code for Base and ChildB

class ChildC : public ChildA {};

class ChildA : public Base
{
void foo(ChildA* a, ChildB* b ChildC* c)
{
a->var; // fine
b->var; // error
c->var; // fine
}
};

john
 
?

=?koi8-r?B?4c7B1M/Mycog+8nSz8vP1w==?=

Because only derived class members has rights to access protected members of a base class :

class base
{
protected:
int v;
};
class der : public base
{
public:
void foo(der *other)
{
this->v = 10; // ok
other->v = 10; // error
}
};
 
J

John Harrison

áÎÁÔÏÌÉÊ ûÉÒÏËÏ× said:
Because only derived class members has rights to access protected members
of a base class :

class base
{
protected:
int v;
};
class der : public base
{
public:
void foo(der *other)
{
this->v = 10; // ok
other->v = 10; // error
}
};

No, that isn't correct. Try compiling it, no compile errors.

john
 

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

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top