1

I'm new to C++. I have searched my question here, but did not find an answer.. So, I have parent and child classes:

class Animal {
protected:
    Animal *_father;
    Animal *_mother;
    string _name;

public:
  ...
};

class Lion: protected Animal {
private:
...
public:
...
};

I have a method in Lion class that has to print the animal itself and its parents names.

So I want to get the _name field of a parent. I have tried to do : _mother->_name
And the error is: 'name' is a protected member of 'Animal'

I'm pretty sure that inheritance should solve this...
I'll be glad for any help!Thanks you all

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
sasha
  • 35
  • 7
  • 1
    Please provide [mcve] - put your second part of the question into code. `this->_name` should work in any `Lion` method. `protected` inheritance has no effect on the inside visibility of `protected` members. – Quimby Jun 12 '19 at 14:27
  • this->_name will give me the name of the current lion.I want to get name of this lion mother/father. – sasha Jun 12 '19 at 14:29
  • @AlexˢᵅˢʰᵅDruzina You can only do that if `_mother`/`_father` are a declared as a `Lion`, not as an `Animal`. As written, it would be legal (if nonsensical from a biological perspective) for `_mother` to be an `Ape` and `_father` to be a `Butterfly`, in which case a `Lion` (reasonably) does not have permission to access its inaccessible members. You could either use `get`/`set` methods for the name (easiest) or involve templating (probably too heavy for now). – Max Langhof Jun 12 '19 at 14:31
  • @AlexˢᵅˢʰᵅDruzina Sorry, I missread the question, in that case the linked question is correct. – Quimby Jun 12 '19 at 14:32
  • You can access `_mother` from Lion instance because of inheritance but `_mother->name` is not public so you can not access it this way. – muaz Jun 12 '19 at 14:34
  • @muaz If `_mother` were a `Lion` everything would be fine. In C++ access is based on the type you are in, not the object you are in. – Max Langhof Jun 12 '19 at 14:36
  • Thanks you all for making it clear! – sasha Jun 12 '19 at 15:02

0 Answers0