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. Therefore, 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.