In the following program i can't access balance value of parent class in the child class. If the child class can access all attributes and methods of parent class, then why i am getting 0 value when i access parent class balance.

Anyone please help, my programming understanding is very little.

#include <iostream.h>
#include <conio.h>

class bal
{

    public:

    int balance;

      bal()
      {
        balance = 0;
      }

      bal(int b)
      {
        balance = b;
      }

      void deposite()
      {
        balance += 3000;
      }

      int show()
      {
        return balance;
      }

};

class childB: public bal
{

    public:

    void withdraw()
      {
        balance -= 500;
      }
};

void main()
{

   bal b(1000);
   childB c;

   cout << "balance from b : " <<b.show() <<endl;
   cout << "balance from c : " <<c.show() <<endl;

getch();
}

It is displaying zero because you never pass a value to balance. You have to make a constructor in your child class that will take an int and pass it to the constructor of the parent class. Just because you create an object of a derived class doesn’t mean it will get the values of the base class you declared first.

add a default constructor to class childB that initializes balance to -99 and see what line 51 shows.

Place a line in the class bal default constructor like
cout << "default constructor class bal called;"
to see if it is called by line 48.

Experiment to see what happens.

This question has already been answered. Start a new discussion instead.