I am learning OOP in C , and I have written this piece of code to learn more about inheritance.
#include<bits/stdc .h>
using namespace std;
class Employee {
public:
string name;
int age;
int weight;
Employee(string N, int a, int w) {
name = N;
age = a;
weight = w;
}
};
// this means the class developer inherits from employee
class Developer:Employee {
public:
string favproglang; //this is only with respect to developer employee
// now we will have to declare the constructor
Developer(string name, int age, int weight, string fpl)
// this will make sure that there is no need to reassign the name, age and weight and it will be assigned by the parent class
:Employee(name, age, weight) {
favproglang = fpl;
}
void print_name() {
cout << name << " is the name" << endl;
}
};
int main() {
Developer d = Developer("Hirak", 45, 56, "C ");
cout << d.favproglang << endl;
d.print_name();
cout << d.name << endl; //this line gives error
return 0;
}
Here the developer class is inheriting from the employee class, but when I am trying to print the name of the developer from the main function cout << d.name << endl;
I am getting this error 'std::string Employee::name' is inaccessible within this context
.
I am not getting why I am getting this error? I have declared all the attributes as public in the parent class. This error is not their when I am trying to access the name
from the developer class itself as you can see in the function print_help()
. Moreover I can also print d.favproglang
from the main function, but then why not d.name
? Any help will be highly appreciated. Thank you.
CodePudding user response:
This is because the default access control for inheritance is "private".
If you change this:
// this means the class developer inherits from employee
class Developer: Employee {
to this:
// this means the class developer inherits from employee
class Developer: public Employee {}
By default, class inheritance is "private" inheritance and struct inheritance is "public" inheritance. Private inheritance means public and protected members of the base class will be treated like private members by the child class.
You can override this default behaviour by explicitly writing public
, private
or protected
in front of the base class name.
Search "c base class members access control" to learn more.
CodePudding user response:
There are 2 solutions(straightforward) to this.
Solution 1
Replace the class
keywords for both the Employee and Developer class with the keyword struct
. Note even if you replace class
keyword for Developer with struct
and leave the class
keyword as it is for Employee then also this will work.
Solution 2
Add the keyword public
in the derivation list as shown in the next line:
class Developer:public Employee