I have to create a class containing both a const and a non-const float. Initialize these using the constructor initializer list.
I cannot find direct examples, and still have problems with “const float ff2” and relevant function.
Assuming that FFloat1 is correctly defined, I would be grateful if someone could comment why the output for all the print options is 3, except for
printf("float =%f\n", FFloat1(ff1) )
The answer for it is
float = 0.000000
include <iostream>
#include <iomanip>
using namespace std;
class MyString {
float ff1;
//const float ff2; -------------------- Does not work
public:
FFloat1(float ff1);
//FFloat2(const float ff2); -------------------- Does not work
void print();
};
Then the constant variables must be initialized in an initialization list. This means that you must have at least a programmer provided constructor because the compiler will be unable to provide a default one.
1 2 3 4 5 6 7 8 9
class MyClass
{
constfloat ff2;
public:
MyClass () //constructor
:ff2(10.9f) //initialize constant objects in initialization list - see Note 1 below
{}
};
Note 1.
Static constant integral members can be initialized in the class declaration
Many thanks to guestfulkan for his/her explanation. How can the example be extended to use constructor initializer list? I tried the following without success
My dificulty in using constructor initializer list with a combination of constant and non-constant variables was resolved with line 20. Is this the only way of formulating for such variables?
The problem here is that you have no default constructor (one that takes no parameters) BUT you have a constructor that take one or more parameters MyClass(float _ff1) then you (the programmer) is responsible to provide the default constructor.
You probably found that you could not do this:
1 2 3 4 5
int main()
{
MyClass ST20a; //ERROR - cannot create a variable using default constructor
ST20a.print20a();
}
so you did this instead:
1 2 3 4 5 6 7
int main()
{
MyClass ST20a = MyClass(3.23415);//the compiler would do this - MyClass ST20a (MyClass(3.23415)) - copy construction
ST20a.print20a();
}