static function

I am so close but I need a push in the right direction. My program works....but it doesn't compute the new interest one I change it to 5.0. Does anyone see what I'm doing wrong????

#include <iostream>
#include <iomanip>
using namespace std;

//declaration
class Savings
{
private:
double balance;
static double rate;
double interest;

public:
Savings();
void showvalues();
static void changeRate();


};

double Savings::rate = 0;

Savings::Savings()
{
balance = 300.00;
rate = 4.0;
interest = balance * rate/100;
}

void Savings::changeRate()
{
rate = 5.0;

}

void Savings::showvalues()
{
cout << "\nBalance = : " << balance << endl;
cout << "Rate: " << rate << endl;
cout << "Interest: " << interest << endl;

return;
}

int main ()
{

Savings::changeRate();
Savings Balance;

cout << "The figures regarding the Savings account are: ";
Balance.showvalues();

Balance.changeRate();

cout << "The new figures on the savings account after the change of rate is: ";
Balance.showvalues();

return 0;
}

Why do you need changeRate() to be static if you have no static data?
You don't have any code to recompute the "interest" variable once the rate is changed. to helios' point, changeRate() should not be a static function, nor should rate be static. And changeRate() needs to recompute the interest.
Just remove the rate initialization in the constructore. As I guess you want to see the result calculated as per changed rate 5.0 instead of 4.0, right?

As you may knew that a static variable/data is a single copy across all the instances of that class. So, your initialization of rate in the consructore would change every time an object of that class instantiated and affect all across the class.

Savings::Savings()
{
balance = 300.00;
//rate = 4.0; //comment it out and run it now
interest = balance * rate/100;
}


Good luck :)
Yes, that is true, but now rate is uninitialized in your interest calculation. And your code doesn't fix the problem either.
I would rather put the calculation part in another function like calculateRate() instead of in a constructor. The constructor should not have an initialization for any static variable.
Topic archived. No new replies allowed.