Predict the output of following C++ programs.
Question 1
1 #include<iostream>
2 #include<string.h>
3 using namespace std;
4
5 class String
6 {
7 char *p;
8 int len;
9 public:
10 String(const char *a);
11 };
12
13 String::String(const char *a)
14 {
15 int length = strlen(a);
16 p = new char[length +1];
17 strcpy(p, a);
18 cout << "Constructor Called " << endl;
19 }
20
21 int main()
22 {
23 String s1("Geeks");
24 const char *name = "forGeeks";
25 s1 = name;
26 return 0;
27 }
Output:
Constructor called
Constructor called
The first line of output is printed by statement “String s1(“Geeks”);” and the second line is printed by statement “s1 = name;”. The reason for the second call is, a single parameter constructor also works as a conversion operator.
Question 2
1 #include<iostream>
2
3 using namespace std;
4
5 class A
6 {
7 public:
8 virtual void fun()
9 {
10 cout << "A" << endl ;
11 }
12 };
13 class B: public A
14 {
15 public:
16 virtual void fun()
17 {
18 cout << "B" << endl;
19 }
20 };
21 class C: public B
22 {
23 public:
24 virtual void fun()
25 {
26 cout << "C" << endl;
27 }
28 };
29
30 int main()
31 {
32 A *a = new C;
33 A *b = new B;
34 a->fun();
35 b->fun();
36 return 0;
37 }
Output:
C
B
A base class pointer can point to objects of children classes. A base class pointer can also point to objects of grandchildren classes. Therefor, the line “A *a = new C;” is valid. The line “a->fun();” prints “C” because the object pointed is of class C and fun() is declared virtual in both A and B. The second line of output is printed by statement “b->fun();”.
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:56:12