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<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
#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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Output of C++ Program | Set 20
- Output of C++ Program | Set 19
- Output of C++ Program | Set 14
- Output of C++ Program | Set 15
- Output of C++ Program | Set 16
- Output of C++ Program | Set 17
- Output of C++ Program | Set 13
- Output of C Program | Set 27
- Output of C Program | Set 23
- Output of C Program | Set 24
- Output of C program | Set 25
- Output of C Program | Set 26
- Output of C Program | Set 28
- Output of C++ Program | Set 11
- Output of C++ Program | Set 12
- Output of C++ Program | Set 10
- Output of C++ Program | Set 1
- Output of C Program | Set 17
- Output of C++ Program | Set 2
- Output of C++ Program | Set 3

