Predict the output of following C++ programs.
Question 1
C
#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
CPP
#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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 May, 2021
Like Article
Save Article