user296113
user296113

Reputation: 101

multiple inheritance

when we say "a member declated as protected is accessible to any class imediately derived from it" what does this mean. in the follwing example get_number function can be accessible by the result class , as per the statement it sould only be accessile to test class.

class student
{    
protected:
    int roll_number;        
public:
    void get_number(int){ cout<< "hello"; }
    void put_number(void) {cout<< "hello"; }
};

class test : public student
{
protected:
    float sub1;
    float sub2;
public:     
    void get_marks(float, float) {cout<< "hello"; roll_number  = 10; }    
    void put_marks(void) {cout<< "hello"; cout << "roll_number = " << roll_number  ; } 
};

class result : public test
{
   float total;
public:
    void display(){cout<< "hello"; roll_number  = 10; }
};

int main()
{
    result student;
    student.get_marks(2.2, 2.2);
    student.put_marks();
    return 0;
}

i changed the code as per the first statement the protected variable roll_number not be accessible upto the result class ?

Upvotes: 0

Views: 175

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57749

If you want class result to not have direct access to data member roll_number you need to change the inheritance access of class test to protected:

class test : protected student
{
};

For more information, see The C++ FAQ Lite: Public and Private Inheritance. Changing how class test inherits from class student also affects how data members in class student are accessed by classes derived from class test.

An alternative to inheritance is for class test to contain a private pointer to an instance of class student, as long as class student is not an abstract class.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839074

You have declared get_number as public so all classes can see it.

Upvotes: 2

Related Questions