accessing base class public member from derived class

寵の児 提交于 2021-02-08 21:23:07

问题


Is it possible to access base class public member from instance of derived class in some other locations in the program.

class base {
public:
    int x;

    base(int xx){
    x = xx;
    }
};

class derived : base {
public:
    derived(int xx) : base(xx){
    }
};

class main {
public:
    derived * myDerived;      

    void m1(){
        myDerived = new derived(5);
        m2(myDerived);  
    }

    void m2(derived * myDerived){
        printf("%i", myDerived->x);
    }    
};

After above code, I got following error.

`error: 'int base::x' is inaccessible`

回答1:


You inherit privately from the base class. What you typically need is public inheritance:

class derived : public base

Here is the FAQ on private inheritance.




回答2:


The problem is that you accidentally use private inheritance here

class derived : base {

This makes all base class members private in the derived class.

Change this to

class derived : public base {

and it will work as expected.




回答3:


You should inherit from base publicly, then.

class derived : public base {
public:
    derived(int xx) : base(xx){
    }
};

Private inheritance is used in very specific circumstances, such as when you have a has-a relationship between two classes, but you also need to override a member of the base class.




回答4:


From outside the class, you can only access public members of public base classes; and inheritance is private by default when you define a class using the class keyword.

To make it accessible, you need public inheritance:

class derived : public base
                ^^^^^^



回答5:


Try:

class derived : public base {
    ...
};



回答6:


Use public inheritance:

class derived : public base {
  ...
};

or

Make x private instead of public and use following code:

class Base {
        int x;
        public:
            Base (int xx) {
                x = xx;
            }
            void display() {
                cout << "x = " << x << endl;
            }
    };

    class Derived : public Base {
        public:
            Derived (int xx) : Base (xx) {
            }
    };

    int main() {
        Derived d1(2);
        Derived *d = new Derived(10);
        d->display();
        d1.display();
        return 0;
    }


来源:https://stackoverflow.com/questions/13159659/accessing-base-class-public-member-from-derived-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!