Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Parent
- {
- int id;
- public:
- Parent() = default;
- Parent(int idP) : id{ idP } { std::cout << "Parent ctor\n"; }
- //virtual const std::string& getName(bool simple = true) const {};
- virtual ~Parent() = default;
- };
- class Child : public Parent
- {
- char symb;
- std::string name;
- public:
- Child(int idP, char symbP, std::string nameP) : Parent{ idP }, symb{ symbP }, name{nameP} { std::cout << "Child ctor\n"; };
- const std::string& getName(bool simple = true) const
- {
- if(simple) return name;
- return name + " class symbol -> " + symb;
- }
- std::string& getName(bool simple = true)
- {
- if (simple) return name;
- return name += " class symbol -> " + symb;
- }
- };
- class Other
- {
- };
- void processParents(Parent& p)
- {
- // try to proces different Parent descendants polymorphically
- }
- int main()
- {
- // static_cast
- // dynamic_cast
- // reinterpret_cast
- // const_cast
- //int numI{ 42 };
- //float numF{ 36.6 };
- //int* ptrI{};
- //float* ptrF{};
- //void* ptrV{ &ptrF };
- //ptrI = reinterpret_cast<int*>(ptrF);
- //ptrI = (int*)ptrF;
- //std::cout << (static_cast<float>(numI) / 9) << '\n';
- Parent* ptrP{};
- //ptrP = static_cast<Other*>(new Child{ 42,'z' });
- //ptrP = static_cast<Parent*>(new Child{ 42,'z',"Straustrup" });
- ptrP = new Child{ 42,'z',"Straustrup" };
- //ptrP = new Parent(13);
- //Parent pappi{ };
- //pappi = *ptrP;
- //std::cout << typeid(*ptrP).name() << " is Parent ? " << std::boolalpha << (typeid(*ptrP) == typeid(Parent)) << '\n';
- //std::cout << dynamic_cast<Child*>(ptrP)->getName() << '\n';;
- Parent* effectivePtr{ dynamic_cast<Child*>(ptrP) };
- //Parent* effectivePtr{ (Child*)(ptrP) };
- if (effectivePtr)
- {
- std::cout << "we've got child! ";
- std::cout << dynamic_cast<Child*>(effectivePtr)->getName() << '\n';
- }
- else
- {
- std::cout << "we've got parent! ";
- }
- //if (typeid(*ptrP) == typeid(Child))
- //{
- // std::cout << "We've got Child! ";
- // std::cout << (((Child*)ptrP)->getName()) << '\n';
- //}
- //else
- //{
- // std::cout << "We've got Parent! ";
- //}
- return 0;
- }
- // RTTI - Runtime type identification
- // A -> B -> C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement