// Casting.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include #include using namespace std; class Person { private: string firstname; string lastname; int age; public: Person(string fname, string lname, int a) :firstname(fname), lastname(lname), age(a) {}; virtual ~Person() {}; // shoud be virtual string GetName() const { return firstname + " " + lastname; }; int GetAge() const { return age; }; void SetName(string const& first, string const& last) { firstname = first; lastname = last; }; void SetAge(int const& newage) { age = newage; }; virtual void Say() { cout << "I am a person and my name is " << GetName() << endl; } }; class Customer : public Person { public: Customer(string fname, string lname, int a) : Person(fname, lname, a) {}; void Say() { cout << "I am a customer of your Bank and my name is " << GetName() << endl; //try protected }; }; class BankAccount { private: string id; public: BankAccount(string ID) :id(ID) {}; void SetID(string const &ID) { id = ID; }; string GetID() const { return id; }; virtual void CalculateFees() {}; }; int main() { //Static cast Customer c1("Shaun", "Black", 26); Person* p = &c1; Customer *pC = static_cast(p); pC->Say(); BankAccount ba("123"); Person* p2; cout << "Customer or Bank Account? " << endl; string answer; cin >> answer; if (answer == "ba") { p2 = dynamic_cast(&ba); //Must have a vitual function } else { p2 = dynamic_cast(p); } if (p2) //we have ability to check in run-time is the pointer was pointing to the cutomer/person. If so the condition is True and we can act accordingly { p2->Say(); } else { cout << "I can not cast the pointer to a customer pointer" << endl; } system("pause"); return 0; }