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<<"
Base Function";
16 }
17 };
18
19 class Derived: public Base
20 {
21 public:
22 Derived()
23 {
24 }
25 virtual void fun()
26 {
27 cout<<"
Derived 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