Show the output of the following program and explain it. #include<iostream> usin
ID: 3840005 • Letter: S
Question
Show the output of the following program and explain it.
#include<iostream>
using namespace std;
class A{
public:
int f(){ return 1; }
virtual int g(){ return 2; }
};
class B : public A{
public:
int f(){ return 3; }
int g(){ return 4; }
};
class C : public A{
public:
int g(){ return 5; }
};
int main(){
A *pa;
A a; B b; C c;
pa = &a; cout << pa->f() << endl; cout << pa->g() << endl << endl;
pa = &b; cout << pa->f() + pa->g() << endl << endl;
pa = &c; cout << pa->f() << endl; cout << pa->g() << endl << endl;
system("pause");
return 0;
}
Explanation / Answer
Output:
1
2
5
1
5
How?
cout << pa->f() << endl; cout << pa->g() << endl << endl;
pa ->f() is base class itself function f() in class A // return 1
pa->g() is base class itself function g() in class A // return 2
pa = &b;
cout << pa->f() + pa->g() << endl << endl;
pa ->f() is base class itself function f() in class A // return 1
pa->g() is derived class function g() in class B // return 4
pa = &c;
cout << pa->f() << endl; cout << pa->g() << endl << endl;
pa ->f() is base class itself function f() in class A // return 1
pa->g() is derived class function g() in class C // return 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.