19. What is function template and class template?
Function templates are special functions that can operate with generic types.
|
Class template have members that use template parameters as types
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
Example:
mypair<int> myobject (115, 30);
20 .What is POLYMORPHISM 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 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 derived classes must implement the DRAW() method. public class CIRCLE::public SHAPE { public void CIRCLE::DRAW() { // TODO drawing circle } }; public class SQUARE::public SHAPE { public void SQUARE::DRAW() { // TODO drawing square } }; 21. What is virtual function? Give an example to explain using/not using virtual function. C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. |
#include<iostream> using namespace std; class Window // Base class for C++ virtual function example { public: virtual void Create() // virtual function for C++ virtual function example // void Create() { cout <<"Base class Window"<<endl; } }; class CommandButton : public Window { public: void Create() { cout<<"Derived class Command Button - Overridden C++ virtual function"<<endl; } }; int main() { Window *x, *y; x = new Window(); x->Create(); y = new CommandButton(); y->Create(); return(0); }
If the function create is declared virtual, the following output is given:
Base class Window
Derived class Command Button - Overridden C++ virtual function
If the function create is not declared virtual, the following output
is given
Base class Window
Base class Window
The base function create is kept calling.