-1

When i run this program the output is "In A" and "In Show". Why cout statements after that are not printing ? I am initializing class B object using member initializer list so the value of of x and y should ideally be 0. Why is this strange behavior ?

class B
{
    int x, y;
public:
    B(int a)
    {

    }
    void show() //what would this print ?
    {
        cout << "In Show";
        cout << "x = " << x << endl;
        cout << "y =" << y;
    }
};

class A
{
    B *b;
public:
    A() : b(0)
    {
        cout << "In A";
        b->show();
    }
};

int main()
{
    A a;
    return 0;
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
Shahid
  • 3
  • 1
  • 1
    Partial duplicate? https://stackoverflow.com/questions/30180417/why-does-an-uninitialized-variable-print-in-c and https://stackoverflow.com/questions/30542801/reading-uninitialized-variable – Galik Nov 16 '18 at 16:19
  • *"I am initializing class B object using member initializer list so the value of of x and y should ideally be 0."* - Where do you initialize `class B`? – Galik Nov 16 '18 at 16:22
  • Even if you would initialize `A::b` with the address of a valid instance of `B` (maybe like `A() : b{ new B{42} } {}`, `b.x` and `b.y` would still contain garbage because they are not initialized with a value in `B`s constructor. They will get *default-initialized* which means simpy: do nothing for `int`s. – Swordfish Nov 16 '18 at 16:23

1 Answers1

2

You are initializing the pointer b with 0, then try to dereference this 0 with b->show().

This is undefined behavior and the fact that anything is printed at all is pure luck.

You need to initialize b with a pointer to a valid B object, for example by allocating one with new B, although I highly advice not to use dynamic memory as a C++ beginner if avoidable.

Considering the rest of your code, probably you simply want b to have type B instead of B*.

If you really want an owning pointer there prefer std::unique_ptr<B> over B*.

Additionally you are not actually initializing Bs members to zero in its constructor. Their values would be indeterminate when show is called. To initialize them to zero you would need something like:

B(int a) : x(0), y(0)
{
}

or if both are supposed to be initialized to the value of a, then:

B(int a) : x(a), y(a)
{
}