Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 295
Mattia Avatar asked May 31 '11 11:05

Mattia


People also ask

How do you access variables from base class?

To access a base class variable hidden by a derived class In an expression or assignment statement, precede the variable name with the MyBase keyword and a period ( . ). The compiler resolves the reference to the base class version of the variable.

Can child class access instance variables of parent class?

The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.

How do you call parent class variables in child class?

Use of super with methods This is used when we want to call the parent class method. So whenever a parent and child class have the same-named methods then to resolve ambiguity we use the super keyword.

How do you access a private variable in child class?

Private variables cannot be used/accessed in child class. But if you want to use them, either you can use it through getters/setters or by making the variable protected (it means you can access the variables in a same package).


1 Answers

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.

like image 109
Kanopus Avatar answered Nov 15 '22 14:11

Kanopus