Advertisement
lordasif

polymorph

May 12th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4.  
  5. class fruit {
  6. public:
  7. fruit() { }
  8. void display() {
  9. cout << "\nDisplay Fruit " << endl;
  10. }
  11. virtual void info() { // virtual function
  12. cout << "I am a fruit" << endl;
  13. }
  14. };
  15.  
  16. class mango : public fruit {
  17. public :
  18. mango() { }
  19. void display() {
  20. cout << "\nDisplay mango" << endl;
  21. }
  22. void info() {
  23. cout << "My name is Mango" << endl;
  24. }
  25. void show() {
  26. cout << "Showing Mango" << endl;
  27. }
  28. };
  29.  
  30. int main() {
  31. fruit *ptr; // pointer to the base class
  32. fruit f; // declare an object of base class
  33. mango m; // declare an object of derived class
  34.  
  35. /* select the object at run time and call the appropriate member function */
  36. ptr = &f; // points to 'fruit' object
  37. ptr->display(); // calls display() of class 'fruit';
  38. ptr->info(); // calls info() of class 'fruit'
  39. ptr = &m; // points to 'mango' object
  40. ptr->display(); // calls display() of class 'fruit' ( we don't want this )
  41. ptr->info(); // calls info() of class 'mango'(since info() is virtual)
  42. //ptr->show(); // compilation error
  43. return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement