Skip to content

Instantly share code, notes, and snippets.

@kateolenya
Last active March 29, 2019 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kateolenya/f9c2710da0a6f455ac966d9bf9a0dd7c to your computer and use it in GitHub Desktop.
Save kateolenya/f9c2710da0a6f455ac966d9bf9a0dd7c to your computer and use it in GitHub Desktop.
Example of diamond problem in C++
#include <iostream>
using namespace std;
class Device {
public:
void turn_on() {
cout << "Device is on." << endl;
}
};
class Computer: public Device {};
class Monitor: public Device {};
class Laptop: public Computer, public Monitor {
/*
public:
void turn_on() {
cout << "Laptop is on." << endl;
}
// uncommenting this function will resolve diamond problem
*/
};
int main() {
Laptop Laptop_instance;
// Laptop_instance.turn_on();
// will produce compile time error
// if Laptop.turn_on function is commented out
// calling method of specific superclass
Laptop_instance.Monitor::turn_on();
// treating Laptop instance as Monitor instance via static cast
static_cast<Monitor&>( Laptop_instance ).turn_on();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment