

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
This document showcases the implementation of polymorphism in c++ through the creation and manipulation of a base class and its derived classes, derived 1 and derived 2. The code demonstrates the use of virtual functions, constructor and destructor overriding, and object creation and destruction.
Typology: Exercises
1 / 3
This page cannot be seen from the preview
Don't miss anything!
C:\Documents and Settings\usman.younis\my ... 2010\Projects\polymorph\polymorph\polymorph.cpp 1
1 #include
C:\Documents and Settings\usman.younis\my ... 2010\Projects\polymorph\polymorph\polymorph.cpp 2
67 68 ~Derived 2 () 69 { cout<<"Derived 2 is now destructed \n"; } 70 }; 71 72 void main() 73 { 74 Base* ptr; 75 76 //Base Starts 77 ptr = new Base; 78 79 cout<<ptr‐>base_function(‐ 5 )<<endl; 80 cout<<ptr‐>increment( 3 )<<endl; 81 82 delete ptr; 83 //Base Ends 84 85 //Derived 1 Starts 86 ptr = new Derived 1 ; 87 88 cout<<ptr‐>base_function(‐ 5 )<<endl; 89 cout<<ptr‐>increment( 2 )<<endl; 90 cout<<ptr‐>decrement( 4 )<<endl; 91 92 delete ptr; 93 //Derived 1 Ends 94 95 //Derived 2 Start 2 96 ptr = new Derived 2 ; 97 98 cout<<ptr‐>increment( 3 )<<endl; 99 cout<<ptr‐>base_function( 98 )<<endl; 100 cout<<ptr‐>decrement( 54 )<<endl; 101 102 //ptr‐>derv 2 _function( 3 ); Not visible 103 104 delete ptr; 105 //Derived 2 Ends 106 107 Derived 1 * ptr 2 ; 108 109 //Derived 1 Starts 110 ptr 2 = new Derived 1 ; 111 112 cout<<ptr 2 ‐>square( 3 )<<endl; 113 cout<<ptr 2 ‐>base_function( 2 )<<endl; 114 cout<<ptr 2 ‐>increment( 3 )<<endl; 115 116 117 delete ptr 2 ; 118 //Derived 1 Ends 119 120 //Derived 2 Starts 121 ptr 2 = new Derived 2 ; 122 123 cout<<ptr 2 ‐>base_function( 45 )<<endl; 124 cout<<ptr 2 ‐>increment( 56 )<<endl; 125 cout<<ptr 2 ‐>decrement(‐ 9 )<<endl; 126 127 delete ptr 2 ; 128 //Derived 2 Ends 129 130 //ptr 2 = new Base; Can't assign this 131 }