Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote