Access Base class variable from child class method

自古美人都是妖i 提交于 2021-01-20 19:43:15

问题


How can I access base class variable from a child method? I'm getting a segmentation fault.

    class Base
    {
    public:
        Base();
        int a;
    };

    class Child : public Base
    {
    public:
        void foo();
    };

    Child::Child() :Base(){

    void Child::foo(){
        int b = a; //here throws segmentation fault
    }

And in another class:

    Child *child = new Child();
    child->foo();

回答1:


It's not good practice to make a class variable public. If you want to access a from Child you should have something like this:

class Base {
public:
  Base(): a(0) {}
  virtual ~Base() {}

protected:
  int a;
};

class Child: public Base {
public:
  Child(): Base(), b(0) {}
  void foo();

private:
  int b;
};

void Child::foo() {
  b = Base::a; // Access variable 'a' from parent
}

I wouldn't access a directly either. It would be better if you make a public or protected getter method for a.




回答2:


class Base
{
public:
    int a;
};

class Child : public Base
{
    int b;
    void foo(){
        b = a;
    }
};

I doubt if your code even compiled!




回答3:


Solved! the problem was that I was calling Child::foo() (by a signal&slot connection) from a non yet existing object.

Thanks for the aswers.



来源:https://stackoverflow.com/questions/6187020/access-base-class-variable-from-child-class-method

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