user7166135 user7166135 - 18 days ago 5
C++ Question

C++ ,Single Inheritance, Garbage Value

#include<iostream>
using namespace std;
class Alpha
{
int a;
public:
void get_a(int x)
{
a = x;
}
int hello()
{
return a;
}
};
class Beta : public Alpha
{
int b, c;
public:
void get_b(int y)
{
b = y;
}
void add()
{
c = hello() + b;
cout << c << endl; // displays garbage value
}
};
int main()
{
Alpha v1;
Beta v2;
v1.get_a(4);
v2.get_b(3);
v2.add();
v2.disp();
return 0;
}


The output of v2.disp() shows garbage value but when I initalise "a" as v2.get_a instead of v1.get_a , it shows the correct answer. New to C++ btw. Please help. Thanks.

Answer

The problem is that you have two different objects that are unrelated to each other. The object v1 is unrelated to the object v2, they are separate and distinct objects. You initialize Alpha::a with v1.get_a(4), that doesn't initialize Beta::a.

A solution to your problem is to use one object:

Beta v;
v.get_a(4);
v.get_b(3);
v.add();
v.disp();
Comments