Created
October 8, 2019 08:43
-
-
Save endavid/5fe5f65e80564d177e551769ac053d6b to your computer and use it in GitHub Desktop.
Multiple inheritance -- how to rename a method of an implemented interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -Wall -o multiple multiple.cpp | |
#include <iostream> | |
// Based on this answer: | |
// https://stackoverflow.com/a/2005142 | |
// I renamed methods for a serialization example. | |
// In this example, there's a "Unicorn" class that knows how to doA and doB, | |
// but user of the respective interfaces do not expect B to get serialized | |
// when they try to serialize A. | |
class InterfaceA | |
{ | |
public: | |
virtual void doA() const = 0; | |
virtual void serialize() const = 0; | |
}; | |
class InterfaceB | |
{ | |
public: | |
virtual void doB() const = 0; | |
virtual void serialize() const = 0; | |
}; | |
class SerializableA: public InterfaceA | |
{ | |
public: | |
virtual void serializeA() const = 0; | |
void serialize() const override | |
{ | |
serializeA(); | |
} | |
}; | |
class SerializableB: public InterfaceB | |
{ | |
public: | |
virtual void serializeB() const = 0; | |
void serialize() const override | |
{ | |
serializeB(); | |
} | |
}; | |
class Unicorn final : public SerializableA, public SerializableB | |
{ | |
public: | |
void doA() const override { std::cout << "Doing A ..." << std::endl; } | |
void doB() const override { std::cout << "Doing B ..." << std::endl; } | |
void serializeA() const | |
{ | |
std::cout << "A's Data" << std::endl; | |
} | |
void serializeB() const | |
{ | |
std::cout << "B's Data" << std::endl; | |
} | |
void serializeAll() const | |
{ | |
serializeA(); | |
serializeB(); | |
} | |
}; | |
int main(int argc, char** argv) | |
{ | |
Unicorn unicorn; | |
unicorn.doA(); | |
unicorn.doB(); | |
unicorn.serializeAll(); | |
InterfaceA& a = unicorn; | |
a.doA(); | |
a.serialize(); | |
InterfaceB& b = unicorn; | |
b.doB(); | |
b.serialize(); | |
} | |
// output: | |
// | |
// Doing A ... | |
// Doing B ... | |
// A's Data | |
// B's Data | |
// Doing A ... | |
// A's Data | |
// Doing B ... | |
// B's Data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment