Not sure how this program compiles without any error.

S

Suresh V

#include <iostream.h>

class A {
protected:
int a;
};

class B : protected A
{
};

class C: private B
{
public:
void assign() {
a = 1;
}
};

int main(){
C* a = new C();
a->assign();
return 0;
}

How can class 'C' has access to Class 'A' data members if class 'C' is
derived as private from class 'B' which intern derives class 'A' as
protected ? please help
 
T

tonydee

#include <iostream.h>

class A {
    protected:
        int a;
};

class B : protected A
{ };

class C: private B
{
   public:
       void assign() {
           a = 1;
       }
};

int main(){
    C* a = new C();
    a->assign();
}

How can class 'C' has access to Class 'A' data members if class 'C' is
derived as private from class 'B' which intern derives class 'A' as
protected ? please help

The way to read this is:
- Class A only grants access to 'a' to derived classes
- Class B is derived from A (hence it can access 'a'), and only grants
access to A (and hence 'a') to its own derived/sub-classes
- Class C is derived from B (hence it can access 'a'), but will keep A
(and hence 'c') hidden from even its derived classes

So, those access specifiers relate to how the base class's members are
exposed to the _next_ level of derived class. Consequently, if you
subclass C, it will not have access to 'a'.

Cheers,
Tony
 
P

Paul Bibbings

Suresh V said:
#include <iostream.h>

class A {
protected:
int a;
};

class B : protected A
{
};

class C: private B
{
public:
void assign() {
a = 1;
}
};

int main(){
C* a = new C();
a->assign();
return 0;
}

How can class 'C' has access to Class 'A' data members if class 'C' is
derived as private from class 'B' which intern derives class 'A' as
protected ? please help

Why do you think that it would not be able to? If you follow it
through: a is protected in class A; class B derives from A by protected
inheritance meaning that a is available to B (being protected in A), and
that it remains protected in B; class C derives from B by private
inheritance, meaning that a (which is protected in B) is available to
class C and is now private in that class. The call a->assign() in main
then behaves no differently (from its point of view) than if you had
written:

class C {
private:
int a;
public:
void assign() {
a = 1;
}
}

int main() {
C *a = new C();
a->assign();
return 0;
}

Regards

Paul Bibbings
 

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,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top