12

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();
Mattia
  • 173
  • 1
  • 1
  • 7

3 Answers3

30

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.

Kanopus
  • 764
  • 5
  • 8
  • Depends of whether the class describes an object or a data structure, and whether in the latter case you want to follow the java bean convention. – yeoman Oct 09 '16 at 12:02
  • In case it's an object, a getter is a possible sign of a design problem. In case it's a data structure, getters and setters can make things like data bindng posssible, and they can follow conventions, like java's beans, thus enabling better tool support. data structures modeled as classes in C++ leave the choice to the developer, though, as getters and setters do not yield any direct technical benefit. – yeoman Oct 09 '16 at 12:05
0
class Base
{
public:
    int a;
};

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

I doubt if your code even compiled!

deepsnore
  • 976
  • 5
  • 13
0

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

Mattia
  • 173
  • 1
  • 1
  • 7