diff options
| -rw-r--r-- | labb4/test-rule-of-three/main.cpp | 74 | ||||
| -rw-r--r-- | labb4/test-rule-of-three/main.hpp | 31 |
2 files changed, 105 insertions, 0 deletions
diff --git a/labb4/test-rule-of-three/main.cpp b/labb4/test-rule-of-three/main.cpp new file mode 100644 index 0000000..ccef31a --- /dev/null +++ b/labb4/test-rule-of-three/main.cpp @@ -0,0 +1,74 @@ +#include <iostream> +#include "main.hpp" + +Base *DerivedA::clone() { + std::cout << "clone da" << std::endl; + return new DerivedA; +} + +Base *DerivedB::clone() { + std::cout << "clone db" << std::endl; + return new DerivedB; +} + +void Base::hello() { + std::cout << 0 << std::endl; +} + +void DerivedA::hello() { + std::cout << 1 << std::endl; +} + +void DerivedB::hello() { + std::cout << 2 << std::endl; +} + +GameState::GameState() { + std::cout << "c" << std::endl; + thing = new DerivedA; +} + +GameState::GameState(const GameState &other) { + std::cout << "cc" << std::endl; + thing = other.thing->clone(); +} + +GameState &GameState::operator=(const GameState &other) { + std::cout << "=" << std::endl; + thing = other.thing; + return *this; +} + +GameState::~GameState() { + std::cout << "d gamestate" << std::endl; + delete thing; + thing = nullptr; +} + +void GameState::switchThing() { + std::cout << "switch" << std::endl; + delete thing; + thing = new DerivedB; +} + +int main(int argc, char *argv[]) { + GameState state; + state.thing->hello(); + std::cout << std::endl; + + GameState copy = state; + state.thing->hello(); + copy.thing->hello(); + std::cout << std::endl; + + copy.switchThing(); + state.thing->hello(); + copy.thing->hello(); + std::cout << std::endl; + + state = copy; + state.thing->hello(); + copy.thing->hello(); + + return 0; +} diff --git a/labb4/test-rule-of-three/main.hpp b/labb4/test-rule-of-three/main.hpp new file mode 100644 index 0000000..5cd7ffb --- /dev/null +++ b/labb4/test-rule-of-three/main.hpp @@ -0,0 +1,31 @@ +struct Base { + virtual ~Base() {} + virtual Base *clone() = 0; + + virtual void hello() = 0; +}; + +struct DerivedA : public Base { + ~DerivedA() = default; + Base *clone() override; + + void hello() override; +}; + +struct DerivedB : public Base { + ~DerivedB() = default; + Base *clone() override; + + void hello() override; +}; + +struct GameState { + GameState(); + + GameState(const GameState &other); + GameState &operator=(const GameState &other); + ~GameState(); + + Base *thing; + void switchThing(); +}; |
