#include #include #include using namespace std; class BaseSquareT { public: BaseSquareT(int cost=10): travelCost{cost} {}; virtual ~BaseSquareT() = default; virtual string Description() const { return "An empty and unremakable land"; } virtual int Cost() const { return travelCost; } protected: int travelCost; }; class RoadSquareT: public BaseSquareT { public: RoadSquareT(int cost=5, int toll=100): BaseSquareT{cost}, tollPrice{toll/**travelCost*/} { //cout << "My parent's travel cost is " << travelCost << endl; }; string Description() const override { //cout << "My parent is " << BaseSquareT::Description() << endl; return "A well maintained road"; } virtual int Toll() const { return tollPrice; } protected: int tollPrice; }; void BadPrint(BaseSquareT square); void BetterPrint(const BaseSquareT & square); void GoodPrint(const BaseSquareT * square); int main() { BaseSquareT base; cout << "Base Informaion " << endl; cout << "\tMovement Cost: " << base.Cost() << endl; cout << "\t" << base.Description() << endl; cout << endl << endl; RoadSquareT road; cout << "Road Informaion " << endl; cout << "\tMovement Cost: " << road.Cost() << endl; cout << "\t" << road.Description() << endl; cout << "\tToll Cost: " << road.Toll() << endl; cout << endl << endl; cout << "--------------------------------" << endl; cout << "The bad print function" << endl; cout << "Base" << endl; BadPrint(base); cout << "Road" << endl; BadPrint(road); cout << endl << endl; cout << "--------------------------------" << endl; cout << "The better print function" << endl; cout << "Base" << endl; BetterPrint(base); cout << "Road" << endl; BetterPrint(road); cout << endl << endl; cout << "--------------------------------" << endl; cout << "The good print function" << endl; cout << "Base" << endl; GoodPrint(&base); cout << "Road" << endl; GoodPrint(&road); return 0; } void BadPrint(BaseSquareT square){ cout << "You enter a square with the bad print function" << endl; cout << "\tMovement Cost: " << square.Cost() << endl; cout << "\t" << square.Description() << endl; } void BetterPrint(const BaseSquareT & square){ cout << "You enter a square with the better print function" << endl; cout << "\tMovement Cost: " << square.Cost() << endl; cout << "\t" << square.Description() << endl; try { const RoadSquareT & road = dynamic_cast(square); cout << "\tToll Cost: " << road.Toll() << endl; } catch (bad_cast & b) { } } void GoodPrint(const BaseSquareT * square){ const RoadSquareT * tmpRoad; cout << "You enter a square with the good print function" << endl; cout << "\tMovement Cost: " << square->Cost() << endl; cout << "\t" << square->Description() << endl; if (nullptr != (tmpRoad = dynamic_cast(square))) { cout << "\tToll Cost: " << tmpRoad->Toll() << endl; } }