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

转载于:https://www.cnblogs.com/iloveyouforever/p/3446118.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值