fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class Base
  5. {
  6. public:
  7. virtual void show_data() {
  8. std::cout<<__PRETTY_FUNCTION__<<std::endl;
  9. }
  10. virtual ~Base(){}
  11. };
  12.  
  13. class Derived: public Base
  14. {
  15. public:
  16. virtual void show_data() override {
  17. std::cout<<__PRETTY_FUNCTION__<<std::endl;
  18. std::cout<<"Just derived"<<std::endl;
  19. std::cout<<"Such useful"<<std::endl;
  20. }
  21.  
  22. };
  23.  
  24. class Special: public Base
  25. {
  26. public:
  27. Special(int num, const std::string &data): secret_num(num), secret_data(data)
  28. {}
  29.  
  30. virtual void show_data() override {
  31. std::cout<<__PRETTY_FUNCTION__<<std::endl;
  32. std::cout<<"Num: "<<secret_num<<std::endl;
  33. std::cout<<"Data: "<<secret_data<<std::endl;
  34. }
  35.  
  36. void set_params(int num, const std::string &data){
  37. secret_num = num;
  38. secret_data = data;
  39. }
  40. private:
  41. int secret_num;
  42. std::string secret_data;
  43. };
  44.  
  45.  
  46. int main()
  47. {
  48. std::vector<Base *> objects{
  49. new Base(),
  50. new Special(1111, "mheh"),
  51. new Derived()
  52. };
  53.  
  54. for (const auto &it: objects)
  55. {
  56. Special *special = dynamic_cast<Special *>(it);
  57. if (special != nullptr)
  58. {
  59. special->show_data();
  60. special->set_params(0, "new data");
  61. special->show_data();
  62. }
  63. else
  64. {
  65. it->show_data();
  66. }
  67. std::cout<<"========="<<std::endl;
  68. }
  69.  
  70. for (auto &it: objects){
  71. delete it;
  72. }
  73. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
virtual void Base::show_data()
=========
virtual void Special::show_data()
Num: 1111
Data: mheh
virtual void Special::show_data()
Num: 0
Data: new data
=========
virtual void Derived::show_data()
Just derived
Such useful
=========