S
S
Sergey Savostin2020-12-06 12:29:57
C++ / C#
Sergey Savostin, 2020-12-06 12:29:57

How to access inherited variable from base class function?

Please answer a noob question. There is such a design:

class Base {
protected:
   int myvar;
   void useBaseVar(){
     cout << myvar << endl; // ожидается вывод 42, а не 10
   }
public:
   Base() : myvar(10) {}
   ~Base() {}
};


class Another : public Base {
protected:
   int myvar;
public:
   Another() : Base(), myvar(42) {}
   ~Another() {}
   void useMyVar() {
     useBaseVar();
   }
};



Another a;
a.useMyVar();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xorknown, 2020-12-06
@savostin

Not sure if you wrote the code correctly. But to simply access the variable whose name you have hidden,
just write the base class name::variable(Base::myvar).
The question is, do you need the myvar variable in Another?
UPD: misread.
Initialize the variable myvar in the inherited class. In Another, you have a completely different variable that has nothing to do with myvar base, just remove it.
If you want to initialize myvar in a constructor then you need to have a base constructor that takes an argument

class Base {
protected:
   int myvar;
   void useBaseVar(){
     cout << myvar << endl; // вывод 42
   }
public:
   Base() : myvar(10) {}
   Base(int  val) : myvar(val) {}
   ~Base() {}
};


class Another : public Base {
public:
   Another() : Base(42) {}
   void useMyVar() {
     useBaseVar();
   }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question