Mattia
Mattia

Reputation: 173

Access Base class variable from child class method

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();

Upvotes: 12

Views: 64818

Answers (3)

Mattia
Mattia

Reputation: 173

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

Upvotes: 0

mechanicker
mechanicker

Reputation: 986

class Base
{
public:
    int a;
};

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

I doubt if your code even compiled!

Upvotes: 1

Kanopus
Kanopus

Reputation: 774

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.

Upvotes: 30

Related Questions