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

#include <iostream> using namespace std; class A { public: virtual void f1() { c

ID: 664078 • Letter: #

Question

#include <iostream>

using namespace std;

class A {

public:

virtual void f1() { cout << "f1 in A "; }

   void f2() { cout << "f2 in A "; }

};

class B : public A {

public:

void f1() { cout << "f1 in B "; }

void f2() { cout << "f2 in B "; }

};

void g(A & x){

x.f1();

x.f2();

int main(){

   A a;

   B b;

   g(a); g(b);

   a.f1(); a.f2();

   b.f1(); b.f2();

}

---------------------------------------------------------------------------------------------------------------------------------------------------------

Explain the each output STEP BY STEP

Explanation / Answer

#include <iostream>

using namespace std;

class A {

public:

virtual void f1() { cout << "f1 in A "; }

     void f2() { cout << "f2 in A "; }

};

class B : public A {

public:

void f1() { cout << "f1 in B "; }

void f2() { cout << "f2 in B "; }

};

void g(A & x){

x.f1();

x.f2();

}

int main(){

    A a;

    B b;

    g(a); g(b);

    a.f1(); a.f2();

    b.f1(); b.f2();

}

OUTPUT

                f1 in A      // It is printed when we called x.f1() ,by passing Class A object a to g

                f2 in A        // It is printed when we called x.f2() ,by passing Class A object a to g

                f1 in B    // It is printed when we called x.f1() ,by passing Class B object b to g, because virtual                                                             is used to call same function in another class

                f2 in A            // It is printed when we called x.f2() ,by passing Class b object b to g

                f1 in A            // It is printed when we called a.f1()

                f2 in A            // It is printed when we called a.f2()

                f1 in B            // It is printed when we called b.f1()

                f2 in B            // It is printed when we called b.f2()