C++/variables definition
Expert: vijayan - 6/2/2009
QuestionHi
could you please tell me about the difference between data member and class variable and also difference between data member and instance variable by giving some examples,i really get confused about it.
thanx
Bita
Answer#include <iostream>
struct account
{
double balance_amount ; // instance data member variable
static double interest_rate ; // class data member variable
};
// define the interest_rate shared by all accounts
double account::interest_rate = 6.7 ;
int main()
{
account ac1, ac2, ac3 ;
// each account has its own balance_amount
ac1.balance_amount = 100.30 ;
ac2.balance_amount = 562.70 ;
ac3.balance_amount = 3455.80 ;
// account::balance_amount = 55.00 ; // **** error *** which account?
std::cout << ac1.balance_amount << '\t' << ac2.balance_amount << '\t'
<< ac3.balance_amount << '\n' ;
// all accounts share a single interest_rate
ac1.interest_rate = 4.30 ; // interest_rate of all accounts set to 4.30
std::cout << ac1.interest_rate << '\t' << ac2.interest_rate << '\t'
<< ac3.interest_rate << '\t' << account::interest_rate << '\n' ;
ac2.interest_rate = 3.10 ; // interest_rate of all accounts set to 3.10
std::cout << ac1.interest_rate << '\t' << ac2.interest_rate << '\t'
<< ac3.interest_rate << '\t' << account::interest_rate << '\n' ;
account::interest_rate = 5.50 ; // ok, interest_rate of all accounts set to 5.50
std::cout << ac1.interest_rate << '\t' << ac2.interest_rate << '\t'
<< ac3.interest_rate << '\t' << account::interest_rate << '\n' ;
}