Wednesday 17 February 2016

Question on static member variable in C++

Question: What is the output of the program written below ?

#include<iostream>
class Account
{
  private:
    int balance;
    static float roi;
  public:
    void setBalance(int b)
    {
      balance = b;
    }
    void showBalance()
    {
      std::cout<<"Balance is : "<<balance<<std::endl;
    }
    static void setRoi(double r)
    {
      roi = r;
    }
    static void showRoi()
    {
      std::cout<<"Roi is : "<<roi<<std::endl;
    }
};
float Account:: roi;
int main()
{
  Account:: setRoi(3.6f);
  Account:: showRoi();
  Account obj;
  obj.setBalance(9999999);
  obj.showBalance();
  std::cout<<"Size of the Account object is : "<<sizeof obj<<std::endl;
  return 0;
}

Answer :
Roi is : 3.6
Balance is : 9999999
Size of the Account object is : 4

Reason :
The static member variable does not belong to the instance of class(i.e it does not belong to the object of the class). So, the object 'obj' has only on variable contained into it, which is 'balance'. And thus the size of the object 'obj' is 4 (size of an integer),

NOTE: this output is in context with the compiler GCC 5.1

1 comment: