开发者

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 b开发者_开发知识库e 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 ?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜