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

Explain why the two calls to function g produces different results in each case:

ID: 3570027 • Letter: E

Question

 Explain why the two calls to function g produces different results in each case:  #include <iostream> using namespace std; class X {     int x; public:     X() { x = 10; }     void f() { cout << "f called " << x <<  endl; } };  class Y : public X {     int y; public:     Y() { y = 20; }     void g() { cout << "g called" << y << endl; } };  int main() {    X* a = new X;    Y* b = new Y;    ((Y*)a)->g();    a = b;    ((Y*)a)->g(); } 

Explanation / Answer

X* a = new X; Y* b = new Y; ((Y*)a)->g(); // Here we are just getting reference 'a' to be converted into (Y*) without creating object.... So the variable 'y' in class Y stores '0' by default... So it will be printed "g called 0" a = b; // We are assigning classY object to classX referrence ((Y*)a)->g(); // Here after assigning classY object to referrence 'a' we are calling method g().. So as we created object for class Y, its variable will be assigned with '20' in the constructor.. So it will be printed "g called 20"

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