Output of C++ Program | Set 10
Predict the output of following C++ programs.
Question 1
#include<iostream> #include<string.h> using namespace std; class String { char *p; int len; public: String(const char *a); }; String::String(const char *a) { int length = strlen(a); p = new char[length +1]; strcpy(p, a); cout << "Constructor Called " << endl; } int main() { String s1("Geeks"); const char *name = "forGeeks"; s1 = name; return 0; } |
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 (See this and this for details).
Question 2
#include<iostream> using namespace std; class A { public: virtual void fun() {cout << "A" << endl ;} }; class B: public A { public: virtual void fun() {cout << "B" << endl;} }; class C: public B { public: virtual void fun() {cout << "C" << endl;} }; int main() { A *a = new C; A *b = new B; a->fun(); b->fun(); return 0; } |
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 (See this for details). The second line of output is printed by statement “b->fun();”.
Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.
Recommended Posts:
- Output of C++ Program | Set 19
- Output of C Program | Set 18
- Output of C Program | Set 23
- Output of C Program | Set 24
- Output of C program | Set 25
- Output of C Program | Set 26
- Output of C Program | Set 28
- Output of C++ Program | Set 11
- Output of C Program | Set 19
- Output of C Program | Set 20
- Output of C++ Program | Set 4
- Output of C++ Program | Set 5
- Output of C++ Program | Set 6
- Output of C Program | Set 21
- Output of C++ Program | Set 7



