The solution in short:
create a protected implementation of printInfo
in both Vampire
and WereWolf
classes (printOnlyVampire
, printOnlyWereWolf
) and call them from VapmireWereWolf
.
Explanation
I happen to know what the original question is so here are the 4 classes:
class Creature {
/** has some creature properties */
public:
virtual void printInfo() {
/** print all creature properties... */
}
}
class Vampire: virtual public Creature {
/** has some Vapmire specific properties */
public:
virtual void printInfo() {
/** print all of the creature properties */
Creature::printInfo();
/** print all Vampire properties... */
}
}
class WereWolf: virtual public Creature {
/** has some WereWolf specific properties */
public:
virtual void printInfo() {
/** print all of the creature properties */
Creature::printInfo();
/** print all WereWolf properties... */
}
}
class VapmireWereWolf: public Vampire, public WereWolf {
/** has some VapmireWereWolf specific properties */
public:
virtual void printInfo() {
/** print all of the Creature + Vampire properties */
Vampire::printInfo();
/** print all of the Creature + WereWolf properties */
WereWolf::printInfo();
/** print all VapmireWereWolf properties... */
}
}
The problem
In the current implementation, calling the VapmireWereWolf
class printInfo
function will cause the Creature
class properties to be printed twice.
Both Vampire
and WereWolf
are calling Creature::printInfo()
in their printInfo
implementation, but we can't change that because we still need them printed in case we have an object of type Vampire/WereWolf
and we want all of his properties printed.
The solution
Create a protected function for Vampire
and WereWolf
which only print's their own info, and call it from VapmireWereWolf
.
class Vampire: virtual public Creature {
/** has some Vapmire specific properties */
public:
virtual void printInfo() {
/** print all of the creature properties */
Creature::printInfo();
printOnlyVampire();
}
protected:
void printOnlyVampire() {
/** print all Vampire properties... */
}
}
class WereWolf: virtual public Creature {
/** has some Vapmire specific properties */
public:
virtual void printInfo() {
/** print all of the creature properties */
Creature::printInfo();
printOnlyWereWolf();
}
protected:
void printOnlyWereWolf() {
/** print all WereWolf properties... */
}
}
class VapmireWereWolf: public Vampire, public WereWolf {
/** has some VapmireWereWolf specific properties */
public:
virtual void printInfo() {
/** print all of the creature properties */
Creature::printInfo();
/** print all of the Vapmire properties */
Vampire::printOnlyVampire();
/** print all of the WereWolf properties */
WereWolf::printOnlyWereWolf();
/** print all VapmireWereWolf properties... */
}
}