Home > Mobile >  Why does this give me an error when using Inheritance
Why does this give me an error when using Inheritance

Time:09-18

I am currently learning Inheritance. The code below works just fine.

#include <iostream>

class Student {
protected:
    double GPA = 3.12;
};

class Employee {
protected:
    int Salary = 1500;
};

class TeachingAssistant: public Student, public Employee {
public: 
    void Print() {
        std::cout << GPA << " " << Salary << "\n";
    }
};

int main() {
    TeachingAssistant TA;
    TA.Print();
}

However this code below does NOT work.

#include <iostream>

class Student {
protected:
    double GPA = 3.12;
};

class Employee: public Student {
protected:
    int Salary = 1500;
};

class TeachingAssistant: public Student, public Employee {
public: 
    void Print() {
        std::cout << GPA << " " << Salary << "\n";
    }
};

int main() {
    TeachingAssistant TA;
    TA.Print();
}

The Error

I only changed one thing in between these two code snippets and it's the addition of "public Student" next to the class Employee. What did I do wrong? Please explain this using simple words/logic.

CodePudding user response:

Field GPA can be accessed from class TeachingAssistant by two ways:

TeachingAssistant -> Student  
TeachingAssistant -> Employee -> Student

You must specify which one you need
For example:

std::cout << Employee::GPA << " " << Salary << "\n";

Another solution is to remove the other inheritance of class Student:

class TeachingAssistant: public Employee {
public:
    void Print() {
        std::cout << GPA << " " << Salary << "\n";
    }
};

CodePudding user response:

Your situation is the following: you have a teaching assistant who's an Student (1) and Employee (2) - however the Employee based on your design is also a student. You end up by having teaching assistant being two students and one employee. C is telling which student's you want me to print the GPA for, hence the ambiguous.

The design is simply wrong in the second code snippet.

TeachingAssistant is both an Employee and a Student: Yes.
An Employee is a Student: No.

  • Related