Predict the output of following C++ programs.
Question 1
1 #include<iostream>
2 using namespace std;
3
4 class Base
5 {
6 public:
7 int fun()
8 {
9 cout << "Base::fun() called";
10 }
11 int fun(int i)
12 {
13 cout << "Base::fun(int i) called";
14 }
15 };
16
17 class Derived: public Base
18 {
19 public:
20 int fun(char x)
21 {
22 cout << "Derived::fun(char ) called";
23 }
24 };
25
26 int main()
27 {
28 Derived d;
29 d.fun();
30 return 0;
31 }
Output: Compiler Error.
In the above program, fun() of base class is not accessible in the derived class. If a derived class creates a member method with name same as one of the methods in base class, then all the base class methods with this name become hidden in derived class.
Question 2
1 #include<iostream>
2 using namespace std;
3 class Base
4 {
5 protected:
6 int x;
7 public:
8 Base (int i)
9 {
10 x = i;
11 }
12 };
13
14 class Derived : public Base
15 {
16 public:
17 Derived (int i):x(i)
18 {
19 }
20 void print()
21 {
22 cout << x ;
23 }
24 };
25
26 int main()
27 {
28 Derived d(10);
29 d.print();
30 }
Output: Compiler Error
In the above program, x is protected, so it is accessible in derived class. Derived class constructor tries to use initializer list to directly initialize x, which is not allowed even if x is accessible. The members of base class can only be initialized through a constructor call of base class.
Following is the corrected program.
1 #include<iostream>
2 using namespace std;
3 class Base
4 {
5 protected:
6 int x;
7 public:
8 Base (int i)
9 {
10 x = i;
11 }
12 };
13
14 class Derived : public Base
15 {
16 public:
17 Derived (int i):Base(i)
18 {
19 }
20 void print()
21 {
22 cout << x;
23 }
24 };
25
26 int main()
27 {
28 Derived d(10);
29 d.print();
30 }
Output:
10
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:34:25