#include <iostream>
class Base {
public:
virtual void printInfo() {
std::cout << "Base class info" << std::endl;
}
};
class Class1 : virtual public Base {
public:
void printInfo() override {
Base::printInfo();
std::cout << "Class1 info" << std::endl;
}
};
class Class2 : virtual public Base {
public:
void printInfo() override {
Base::printInfo();
std::cout << "Class2 info" << std::endl;
}
};
class Class3 : public Class1, public Class2 {
public:
void printInfo() override {
Class1::printInfo();
Class2::printInfo();
std::cout << "Class3 info" << std::endl;
}
};
int main() {
Class3 obj;
obj.printInfo();
return 0;
}
Here is the general idea of what my code looks like, hierarchy untouched, code simplified. I want Class 3 printInfo function to output
Base class info
Class1 info
Class2 info
Class3 info
But I obviously get
Base class info
Class1 info
Base class info
Class2 info
Class3 info
What can you do about it?
Of course, you could just write it simply, without calling to other printInfo functions from parents and grandparents, it does work, but that makes maintaining and scaling hard.
Is there any way to automate this in C++ without using additional libraries?
You explicitly call
Class1::printInfo();andClass2::printInfo();and those functions explictly callBase::printInfo();so they are doing just want you've ordered them to do. You could add aboolto theprintInfofunction to decide if the base(s) should be called.Example:
Demo
Another option is to keep a
printedstate in each class, but then you'll have to reset that manually after printing.Example:
Demo