• +91 9723535972
  • info@interviewmaterial.com

CPlusPlus Interview Questions and Answers

Question - Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE

Answer - 1. POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call. in C++ it is attained by using a keyword virtual Example public class SHAPE { public virtual void SHAPE::DRAW()=0; } Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated public class CIRCLE::public SHAPE { public void CIRCLE::DRAW() { // TODO drawing circle } } public class SQUARE::public SHAPE { public void SQUARE::DRAW() { // TODO drawing square } } now from the user class the calls would be like globally SHAPE *newShape; When user action is to draw public void MENU::OnClickDrawCircle(){ newShape = new CIRCLE(); } public void MENU::OnClickDrawCircle(){ newShape = new SQUARE(); } the when user actually draws public void CANVAS::OnMouseOperations(){ newShape->DRAW(); } 2. class SHAPE{ public virtual Draw() = 0; //abstract class with a pure virtual method }; class CIRCLE{ public int r; public virtual Draw() { this->drawCircle(0,0,r); } }; class SQURE public int a; public virtual Draw() { this->drawRectangular(0,0,a,a); } }; Each object is driven down from SHAPE implementing Draw() function in its own way.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners