sorry if this is an obvious one but I've searched around and I'm still unclear about how to solve this issue. Here is my code:
#include <iostream>
#include <string>
using namespace std;
class PermMagnet {
public:
string name;
int ac_rating;
int dc_rating;
int mass_kg;
int age;
PermMagnet(){
// default constructor
name = "";
ac_rating = 0; dc_rating = 0;
mass_kg = 0; age = 0;
}
PermMagnet(string c_name, int c_ac_rating, int c_dc_rating, int c_mass_kg, int c_age){
// parameterised constructor
name = c_name;
ac_rating = c_ac_rating;
dc_rating = c_dc_rating;
mass_kg = c_mass_kg;
age = c_age;
}
string get_owner(){
return owner;
}
string get_classifier(){
return classifier;
}
int get_coil_count(){
return coil_num;
}
protected:
string location = "facility hall";
private:
string owner = "Unspecified Staff";
string classifier = "MAG-DP-";
const int coil_num = 2;
};
class ElecMagnet : public PermMagnet {
public:
// inherit base class constructors
using PermMagnet::PermMagnet;
string get_location(){
return location;
}
private:
string owner = "Specified Staff";
string classifier = "MAG-QD-";
const int coil_num = 4;
};
int main() {
// Create object using default constructor
PermMagnet perm1;
cout << "'perm1' age: " << perm1.age << endl;
// Create object using parameterised constructor
PermMagnet perm2("PermMagnet 2", 380, 400, 1500, 35);
cout << "'perm2' age: " << perm2.age << " | 'perm2' name: " << perm2.name << endl;
cout << "Owner of 'perm2': " << perm2.get_owner() << endl;
cout << "Upper current bound of 'perm2': " << perm2.get_current_limit("upper") << "A" << endl;
cout << "Number of coils in 'perm2': " << perm2.get_coil_count() << endl << endl;
// Create a ElecMagnet (derived class) object
ElecMagnet elec1("ElecMagnet 1", 170, 200, 850, 27);
cout << elec1.get_classifier() << endl;
cout << elec1.get_coil_count() << endl;
return 0;
}
The output of this code is:
'perm1' age: 0
'perm2' age: 35 | 'perm2' name: PermMaget 2
Owner of 'perm2': Unspecified Staff
Upper current bound of 'perm2': 780A
Number of coils in 'perm2': 2
MAG-DP-
2
Process finished with exit code 0
As you can see, I want "owner", "classifier" and "coil_num" to be private members that cannot be changed by the user. These also vary depending on the class in question.
The problem:
The problem is the last two lines of the output. When the derived class (ElecMagnet) inherits the public functions that return these members, it returns the members of the base class; not it's own. You can see this because it returns the "classifier" and "coil_num" of the PermMagnet class.
Does anyone know why the derived class is behaving this way? Shouldn't it access its own private members rather than the base?