Open In App

Output of C++ Program | Set 18

Predict the output of following C++ programs.

Question 1




#include <iostream>
using namespace std;
  
template <int N>
class A {
   int arr[N];
public:
   virtual void fun() { cout << "A::fun()"; }
};
  
class B : public A<2> {
public:
   void fun() { cout << "B::fun()"; }
};
  
class C : public B { };
  
int main() {
   A<2> *a = new C;
   a->fun();
   return 0;
}

Output:

B::fun()

In general, the purpose of using templates in C++ is to avoid code redundancy.  We create generic classes (or functions) that can be used for any datatype as long as logic is identical. Datatype becomes a parameter and an instance of class/function is created at compile time when a data type is passed. C++ Templates also allow nontype (a parameter that represents a value, not a datatype) things as parameters.
In the above program, there is a generic class A which takes a nontype parameter N. The class B inherits from an instance of generic class A. The value of N for this instance of A is 2. The class B overrides fun() of class A. The class C inherits from B. In main(), there is a pointer ‘a’ of type A that points to an instance of C. When ‘a->fun()’ is called, the function of class B is executed because fun() is virtual and virtual functions are called according to the actual object, not according to pointer. In class C, there is no function ‘fun()’, so it is looked up in the hierarchy and found in class B.


Question 2




#include <iostream>
using namespace std;
  
template <int i>
int fun()
{
   i =20; 
}
  
int main() {
   fun<4>();
   return 0;
}

Output:

 Compiler Error

The value of nontype parameters must be constant as they are used at compile time to create instance of classes/functions. In the above program, templated fun() receives a nontype parameter and tries to modify it which is not possible. Therefore, compiler error.


Article Tags :