Output of C++ Program | Set 18

 

  Predict the output of following C++ programs.

Question 1

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <int N>
 5 class A 
 6 {
 7     int arr[N];
 8 public:
 9     virtual void fun() 
10     { 
11         cout << "A::fun()"; 
12     }
13 };
14 
15 class B : public A<2> 
16 {
17 public:
18     void fun() 
19     { 
20         cout << "B::fun()"; 
21     }
22 };
23 
24 class C : public B 
25 { 
26 };
27 
28 int main() 
29 {
30     A<2> *a = new C;
31     a->fun();
32     return 0;
33 }

  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

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <int i> int fun()
 5 {
 6     i =20; 
 7 }
 8 
 9 int main() 
10 {
11     fun<4>();
12     return 0;
13 }

  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.
  

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-27  16:53:31

posted @ 2013-11-27 16:54  虔诚的学习者  阅读(232)  评论(0编辑  收藏  举报