0

Hi I have following code in which i am using protected inheritance

#include<iostream>
#include<string>

using namespace std;

class Animal
{
protected:
    int age;
    string name;
public:
    void setAge(int a)
    {
        this->age = a;
    }
    void setName(string n)
    {
        this->name = n;
    }
    int getAge() const
    {
        return age;
    }
     string getName() const
    {
        return name;
    }
};

class Dog : protected Animal
{
public:
    string setBreed(string n)
    {
        return this->breed = n;
    }
    string getBreed()
    {
        return breed;
    }


private:
    string breed;
};


int main()
{
    int a;
    string n, b;
    Dog D;
    cout << "Enter the name of the Dog: ";
    cin >> n;
    cout << "Enter the age of the Dog: ";
    cin >> a;
    cout << "Enter the breed of the Dog: ";
    cin >> b;
    D.setName(n);//set name is not accesible
    D.setAge(a);
    D.setBreed(b);
    cout << "The name of the animal is: " << D.getName() << endl;
    cout << "The age of the animal is: " << D.getAge() << endl;
    cout << "Breed of the dog: " << D.getBreed() << endl;
}

I want to access set name and get name from base class using derived class object as i am implementing protected inheritance the code doesn't compile. So how can i aceess setters and getters without using public inheritance and using derived class object?

  • Use public inheritance rather than protected. You want let everyone know that a Dog is an Animal. – n. m. could be an AI Feb 28 '16 at 07:58
  • You are using the inheritance wrong, as n.m. stated. Check [this answer](http://stackoverflow.com/a/1372858/5583153) and see if you can get a better understanding of the concept. – Nacho Feb 28 '16 at 08:18
  • Possible duplicate of [Difference between private, public, and protected inheritance](http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance) – Nacho Feb 28 '16 at 08:21
  • i know i can access using public inheritance but is there any way to access using protected inheritance – user3732637 Feb 29 '16 at 05:05

0 Answers0