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();
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.
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.
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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With