I have a base class of Builder and a derived class of type SeniorBuilder. SeniorBuilder has the same attributes as Builder plus an extra attribute int experiance
I have created a variety of different Builder and SeniorBuilder and placed them into a dynamically memory allocated array Builder* builders
. all attriutes are privated so if i wanted to utilize the value of the attribute I have created functions to return that value. Example:
int Builder::getAbility() {
return ability;
}
I need to iterate through the builder array and print out the experaince attribute. By default, if its a builder i want to print 0, but if it’s a SeniorBuilder i want to print its value that it was given in its constructor. I tried to use virtual and override to create functions to return the correct values but it is always returning 0 despite being used with a SeniorBuilder. How do I fix this issue?
class Builder {
protected:
int ability;
int variability;
int seniorBit;
string name;
public:
virtual int getExperiance() const { return 0; }
};
class SeniorBuilder : public Builder {
private:
int experiance;
public:
int getExperiance() const override {
return experiance;
}
};
//Write Senior Builder Table
cout << "Senior Builder List" << endl;
cout << setw(15) << "Name" << setw(15) << "Ability" << setw(15) << "Variability" << setw(15) << "Experiance" << endl;
for (int i = 0; i < builderLength; i++) {
if (builders[i].getSeniorBit() == 1) {
cout << setw(15) << builders[i].getName() << setw(15) << builders[i].getAbility() << setw(15) << builders[i].getVariability() << setw(15) << builders[i].getExperiance() << endl;
}
}
//Write Builder Table
cout << "Builder List: " << endl;
cout << setw(15) << "Name" << setw(15) << "Ability" << setw(15) << "Variability" << endl;
for (int i = 0; i < builderLength; i++) {
if (builders[i].getSeniorBit() == 0) {
cout << setw(15) << builders[i].getName() << setw(15) << builders[i].getAbility() << setw(15) << builders[i].getVariability() << endl;
}
}
cout << endl;
I tried using the virtual and override keyword but it is only using the original function given to the Builder class and never the overridden function given to the SeniorBuilder even though the function is being used on a seniorBuilder type due to the if statements as all SeniorBuilders will have their seniorBit = 1.
rafaelzoric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.