class Account {
public:
// interface functions here
void applyint() { amount += amount * interestRate; }
//Static object are the same for all class objects
staticdouble rate() { return interestRate; }
staticvoid rate(double ir){
interestRate=ir; // sets a new rate
}
private:
std::string owner;
double amount;
//Static object are the same for all class objects
//Instead, there is a single interestRate
//object that is shared by all objects of type Account
staticdouble interestRate;
staticdouble initRate();
};
Account ac1;
Account *ac2 = &ac1;
// define and initialize static class member
// double Account::interestRate = initRate();
// Setting global interest rate
ac1.rate(0.06);
// the functions below retrieve the global rate
// equivalent ways to call the static member rate function
double rate;
rate = ac1.rate(); // through an Account object or reference
rate = ac2->rate(); // through a pointer to an Account object
//rate = Account::rate(); // directly from the class using the scope operator
cout<<ac1.rate()<<'\n';
cout<<ac2->rate()<<'\n';
when i build i am getting the following error:
main.o:G:\eclipse_workspace\cpp_lippman_5_class\Debug/..//Account.hpp:21: undefined reference to `Account::interestRate'
main.o:G:\eclipse_workspace\cpp_lippman_5_class\Debug/..//Account.hpp:21: undefined reference to `Account::interestRate'
main.o:G:\eclipse_workspace\cpp_lippman_5_class\Debug/..//Account.hpp:24: undefined reference to `Account::interestRate'
main.o:G:\eclipse_workspace\cpp_lippman_5_class\Debug/..//Account.hpp:24: undefined reference to `Account::interestRate'
when i remove the static keyword the project builds fine
..\main.cpp: In function 'int main()':
..\main.cpp:24:18: error: invalid use of qualified-name 'Account::interestRate'
..\main.cpp:25:27: error: invalid use of qualified-name 'Account::initRate'
Build error occurred, build is stopped
Define the body of both Account::rate( ) methods outside the class definition. As Ivan said, it's recommended that you place your definitions within a source module.
By the way, you may not know it, but the compiler will probably implicitly in-line both of those Account::rate( ) methods, assuming you have the correct optimization flags set :)