Output of C++ Program | Set 18

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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<2>. The class C inherits from B. In main(), there is a pointer ‘a’ of type A<2> 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.