Hello again
I am a bit confused about how to show a constant in a class constructor. I have a savings account class (A child class of Account) which has a constant interest rate. I have it in my class as a static constant double INTEREST_RATE;. Then outside of my class I have given it a value double Savings::INTEREST_RATE = 0.03;. I also have a double getInterestRate() which returns INTEREST_RATE;. I just don't know how to show it in the class constructor. Here is what I have. In anticipation, thank you.

Savings::Savings (int acctNum, double bal, const double rate) :
Account (acctNum, bal), getInterestRate() //I know this is wrong, 
                                          //it is just the last thing I tried
{}

Recommended Answers

All 5 Replies

Not sure what you mean by "show" a constant. If you're trying to declare a constant, do so in the definition of your class.

class Savings
{
private
   const double INTEREST_RATE = 0.03;
.
.
.
};

If I understand what you're trying to do here.

Actually, that was not my question, but you have solved another issue I had, I was not aware you could initialize constants within your class, I thought you had to do it outside the class. My problem is how to show it in the constructor. Usually you would have something like Savings::Savings (int num, double bal, double rate)
{accountNum = num;
balance = bal;
INTEREST_RATE = rate;} //this shouldn't work because it is a constant.
I want to know how to show it here

I still don't know what you mean by "show it in the constructor." As a constant, it shouldn't require initialization, so you shouldn't have to provide a parameter for it.

I have to confess I've never done this, but I think when you instantiate a new object, it will get its own copy of the const member, with no help needed from you in the constructor.

That makes sense, I do make life hard for myself.
thanks again
Patty

OK, well, I could be wrong about this, so if it doesn't work right, report back.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.