Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Output of C++ Program | Set 18

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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


My Personal Notes arrow_drop_up
Last Updated : 01 Apr, 2017
Like Article
Save Article
Similar Reads