0
#include <iostream>
#include <string>
using namespace std ;
enum COLOR { Green, Blue, White, Black, Brown } ;
class Animal {
public :
    Animal() : _name("unknown") {
        cout << "constructing Animal object "<< _name << endl ;
    }
    Animal(string n,COLOR c) : _name(n),_color(c) {
        cout << "constructing Animal object "<< _name << endl ;
    }

    ~Animal() {
        cout << "destructing Animal object "<< _name << endl ;
    }
    void speak() const {
        cout << "Animal speaks "<< endl ;
    }
    void move() const { }
private :
    string _name;
    COLOR _color ;
};
class Mammal:public Animal{
public:
    Mammal(string n,COLOR c):Animal(n,c){
        cout << "constructing Mammal object "<< _name << endl ;
    }
    ~Mammal() {
        cout << "destructing Animal object "<< _name << endl ;
    }
    void eat() const {
        cout << "Mammal eat " << endl ;
    }
};

I just started transitioning from java to C++ today, am practicing some object oriented coding to know the differences.

In the above code, I am unable to access _name from mammal class.

Does the mammal class not inherit private attributes? In this case, do I have to re-create those attributes for every inheritances?

Kakayou
  • 598
  • 1
  • 8
  • 16
  • 2
    Your title doesn't match your body - do you actually mean you're confused by inheritance in C++? – Jon Skeet Apr 23 '16 at 06:31
  • 4
    private is private. If you want the member variables to be visible from a derived class, put them in a ``protected`` section. – BitTickler Apr 23 '16 at 06:33
  • 1
    ... Or public. BTW - C++ does not have package protection – Ed Heal Apr 23 '16 at 06:34
  • 1
    The private members are in there, but only the base class and its friends can see and use them. Sub classes can only see public and protected members. – user4581301 Apr 23 '16 at 07:09
  • Possible duplicate of [Do subclasses inherit private fields?](http://stackoverflow.com/questions/4716040/do-subclasses-inherit-private-fields) – philipxy Nov 13 '16 at 00:46

2 Answers2

2

You are correct that you cannot access the private attributes of Animal from within Mammal. However, this isn't new if you're coming from Java - it works the same there.

See this link for an example: Do subclasses inherit private fields?

Community
  • 1
  • 1
nhouser9
  • 6,730
  • 3
  • 21
  • 42
1

You cannot access outside private variable of class, here _name is private scope variable of class . Derived class aslo cannot access private scope items from base . To solve this problem , you can declare _name as protected , it will accessed derived class .

Venkata Naidu M
  • 351
  • 1
  • 6