Is this valid C++ (protected member of base accessed in derived class function)

S

Shelly Adhikari

class B {
public:
B() { }
~B() { }
protected:
int abc;
void g() {}
};

class C : public B {
public:
void f(B* p) {
p->g(); // Should this be an error?
int m = p->abc; // Should this be an error?
int n = abc;
g();
}
};

int main() {
B* y = new B();
C x;
x.f(y);
}

If you could also point me to the ISO C++ standard section and page
number, it would be great.
 
?

=?iso-8859-1?Q?Juli=E1n?= Albo

Shelly Adhikari escribió:
class B {
public:
B() { }
~B() { }
protected:
int abc;
void g() {}
};

class C : public B {
public:
void f(B* p) {
p->g(); // Should this be an error?
int m = p->abc; // Should this be an error?

Yes, they are errors. You have access only to a the B that is part of a
C, not to a unrelated B.

Regards.
 
R

Ron Natalie

Shelly Adhikari said:
p->g(); // Should this be an error?
int m = p->abc; // Should this be an error? Yes, these are both errors.
int n = abc;
g();
These are OK.

Protected only lets you get at your own instances (this's) subobjects.
 
R

red floyd

Shelly said:
[protected member access question redacted]

To whoever maintains the FAQs:

Is this one in the FAQs? It's been asked at least five times in the past week. If it isn't,
it should be in there.
 

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,070
Latest member
BiogenixGummies

Latest Threads

Top