I want to set the value of a const float in derived class.How can I do this.
I have declared it in its header file in protected area
const float prate;
do i set it in its header file or implementation file.
if i have to set it in implementation file then how.
my header file name is "fixeddepositamount.h"
implementation file for this "fixeddepositamount.cpp"
You would have to set this when you contstruct your class.
1 2 3 4 5 6 7 8
class Derived : public Base
{
public:
Derived() : pRate(1.23) {}
protected:
staticconstfloat prate;
};
You can't change a protected member that's const through normal assignment I don't believe.
Plus I don't think Hammurabi's idea would work if it were a private or public member.
Hammurabi is correct. You must initialize a static const member globally (his approach works even when protected/private). I believe exceptions are made for integer types, where you can initialize them right in the class (never understood why you could do that with integers but not with floats).
Computerquip is also correct, in that his approach is what you do when the const member is non-static const.
Of course non-static means that every instance of the class may have a different value for 'prate'. So if 'prate' is to be the same for every instance of the class, then you probably want static const, in which case you should go with Hammurabi's solution.
The question is kind of bizarre. If you want the derived class to specify a value for the const that is defined in the base class, there is a way to do it. Is that what the OP is trying to do? The base class must have a constructor that the derived class can call from its initializer list. It could pass in a value that could subsequently be used by the base class constructor's initializer list.
class BaseFoo
{
public:
BaseFoo(constint value) : m_x(value) { std::cout << "BaseFoo::m_x = " << m_x << std::endl; }
~BaseFoo() {}
private:
constint m_x;
};
class DerivedFoo : public BaseFoo
{
public:
// Derived foo can be constructed with a value
DerivedFoo(constint value) : BaseFoo(value) { }
~DerivedFoo() {}
};
int main ()
{
// for each case, the base class will have a different constant value to initialize its
// member.
DerivedFoo foo1(5);
DerivedFoo foo2(10);
return 0;
}
If the base class is closed and does not give you an approprate constructor and the constant is accesable from the derived class the you can cast away the const in the derived constructor. Casting is only ever good as a last option but it is provided exaclty for such a situation.
The follow snippit of code demos what I mean
#include <iostream>
struct B
{
B() : i( 0 ) {};
void print_i() { std::cout << " Value of i is " << i << std::endl; };
const int i;
};
struct D : B
{
D() { const_cast< int& >( i ) = 1; };
};
int main()
{
B b; b.print_i();
D d; d.print_i();
return 0;
}