Access a base class variable from a child class method

How can I access a base class variable from a child method? I get a segmentation error.

    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();
+3
source share
3 answers

It is not recommended to use a variable of class public. If you want to access afrom 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 would not directly contact a. It would be better if you use the method publicor protectedgetter for a.

+14
source
class Base
{
public:
    int a;
};

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

I doubt your code is even compiled!

0
source

! , Child:: foo() ( ) .

.

-2
source

All Articles