Skip to content

Instantly share code, notes, and snippets.

@alekseyl1992
Created November 12, 2015 09:18
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 alekseyl1992/7adf9a738d0c637e7b17 to your computer and use it in GitHub Desktop.
Save alekseyl1992/7adf9a738d0c637e7b17 to your computer and use it in GitHub Desktop.
Two phase C++ virtual invocation
#include <exception>
#include <stdexcept>
#include <string>
class NotImplementedException : public std::runtime_error {
public:
NotImplementedException(const std::string& str)
: std::runtime_error(str) {
}
};
class Player;
class Obstacle;
class WorldObject {
public:
virtual bool collidesWith(WorldObject& other) {
throw NotImplementedException(__PRETTY_FUNCTION__);
}
virtual bool collidesWith(Obstacle& other) {
throw NotImplementedException(__PRETTY_FUNCTION__);
}
virtual bool collidesWith(Player& other) {
throw NotImplementedException(__PRETTY_FUNCTION__);
}
};
class Player : public WorldObject {
public:
Player(int x) : _x(x) {}
bool collidesWith(WorldObject& other) override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return other.collidesWith(*this);
}
private:
int _x;
friend class Obstacle;
};
class Obstacle : public WorldObject {
public:
Obstacle(int y) : _y(y) {}
bool collidesWith(Player& other) override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return _y > other._x;
}
private:
int _y;
};
class NotComparable : public WorldObject {
public:
};
int main() {
NotComparable nc;
Player p(1);
Obstacle o(2);
WorldObject& rp = p;
WorldObject& ro = o;
rp.collidesWith(ro);
//nc.collidesWith(rp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment