fork download
  1.  
  2.  
  3. #include <iostream>
  4. using namespace std;
  5. class B
  6. {
  7. public:
  8. virtual void display() /* Virtual function */
  9. { cout<<"Content of base class.\n"; }
  10. };
  11.  
  12. class D1 : public B
  13. {
  14. public:
  15. void display()
  16. { cout<<"Content of first derived class.\n"; }
  17. };
  18.  
  19. class D2 : public B
  20. {
  21. public:
  22. void display()
  23. { cout<<"Content of second derived class.\n"; }
  24. };
  25.  
  26. int main()
  27. {
  28. B *b;
  29. D1 d1;
  30. D2 d2;
  31.  
  32. /* b->display(); // You cannot use this code here because the function of base class is virtual. */
  33.  
  34. b = &d1;
  35. b->display(); /* calls display() of class derived D1 */
  36. b = &d2;
  37. b->display(); /* calls display() of class derived D2 */
  38. return 0;
  39. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Content of first derived class.
Content of second derived class.