Reputation: 556
Consider the following code:
#include <list>
#include <iostream>
class test{
private:
std::list<double> lst;
public:
int get_size(){
return lst.size();
}
};
class derived : public test{
private:
std::list<double> lst;
public:
derived(int u=8){
for (int k =0 ; k < u; ++k){
int n = lst.size();
lst.push_back(0);
}
}
};
int main(){
derived obj = derived();
std::cout << obj.get_size() << "\n";
return 0;
}
I'm trying to understand why the output of the above code isn't 8
. I thought that the idea of inheritance allows one to use member functions of the base class in the derived class, but it seems that this isn't really working here. Of course I could make the get_size
function virtual
in the base class and then copy paste the code into the derived class and add override
, but this seems really weird, since in this case I could just re-implement the function anyways... So can somebody explain how we need to modify the code from above to get the output 8
?
Upvotes: 0
Views: 37
Reputation:
You're not using the list
from test
. You're declaring a new list
and using that instead in your constructor for derived
.
On the other hand, size()
is using the list
from test
.
If you want to add to the test
list
from inside derived
, you should make test
's list protected
, not private. And you should remove the list
with a duplicate name from derived
.
Upvotes: 1
Reputation: 8215
The lst
in your derived
class is not the same one as used in your base class.
You should make lst
protected
instead of private
in your test
base class.
Then you can use the same variable in the derived class. Of course you also need to delete the lst
declaration in your derived class.
Upvotes: 1