Output of C++ Program | Set 3

本文详细解析了C++中类的继承机制,包括多层继承下函数调用顺序,以及如何正确使用虚拟函数避免构造/析构期间的错误调用。

 

 

  Predict the output of below C++ programs.

  Question 1

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class P 
 5 {
 6 public:
 7     void print()
 8     { 
 9         cout <<" Inside P::"; 
10     }
11 };
12 
13 class Q : public P 
14 {
15 public:
16     void print()
17     { 
18         cout <<" Inside Q::"; 
19     }
20 };
21 
22 class R: public Q 
23 {
24 };
25 
26 int main(void)
27 {
28     R r;
29     r.print();
30     return 0;
31 }

  Output: Inside Q::

  The print function is not defined in class R. So it is looked up in the inheritance hierarchy. print() is present in both classes P and Q, which of them should be called?

  The idea is, if there is multilevel inheritance, then function is linearly searched up in the inheritance heirarchy until a matching function is found.


  Question 2

 1 #include<iostream>
 2 #include<stdio.h>
 3 
 4 using namespace std;
 5 
 6 class Base
 7 {
 8 public:
 9     Base()
10     {
11         fun(); //note: fun() is virtual
12     }
13     virtual void fun()
14     {
15         cout<<"\nBase Function";
16     }
17 };
18 
19 class Derived: public Base
20 {
21 public:
22     Derived()
23     {
24     }
25     virtual void fun()
26     {
27         cout<<"\nDerived Function";
28     }
29 };
30 
31 int main()
32 {
33     Base* pBase = new Derived();
34     delete pBase;
35     return 0;
36 }

  Output: Base Function

  When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object.

  Because of this difference in behavior, it is recommended that object’s virtual function is not invoked while it is being constructed or destroyed.

 

 

 

  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  15:05:32

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值