Last active
March 29, 2019 11:34
-
-
Save kateolenya/f9c2710da0a6f455ac966d9bf9a0dd7c to your computer and use it in GitHub Desktop.
Example of diamond problem in C++
This file contains 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
#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