2
#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.

  • 1
    What is `disp`? I don't see it in your code. – Some programmer dude Nov 16 '16 at 08:29
  • 1
    Also your naming is a little weird. You have functions named `get` that doesn't actually "get" anything but instead *set* values. – Some programmer dude Nov 16 '16 at 08:30
  • I'm sorry, disp was actually a function that was meant to print the value of the variable c. Forgot to add it since I was editing the code. But why garbage value is shown if I have already initialised the variable a. Thanks once again. – user7166135 Nov 16 '16 at 08:34

1 Answers1

3

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();
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621