Let's say I have a class defined as follows:
class foo{};
now, this is perfectly acceptable;
foo f;
how come this is a compiler error? (uninitialized const ‘f’
)
const foo f;
Why do we have to do this?
const foo f = foo();
I know why we can't do this..
const foo f(); // though it compiles..
Interestingly, the following is valid:
const std::string f;
So what is missing from foo
?
I realize that there are three questions there and it's bad form, but I'm hoping someone can clear this up for me in one answer.
EDIT: please feel free to close it if it's stupid...
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon.
A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
Use the readonly modifier to declare constants in a class. When a class field is prefixed with the readonly modifier, you can only assign a value to the property inside of the classes' constructor. Assignment to the property outside of the constructor causes an error.
A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .
Your class is a POD (essentially because it doesn’t provide a default constructor). POD variables are not initialized upon declaration. That is, this:
foo x;
does not initialize x to a meaningful value. This has to be done separately. Now, when you declare it as const
, this may never happen because you cannot assign to or change x
any more.
Consider the equivalence to int
:
int x; // legal const int y; // illegal
As you have noticed, using std::string
instead of foo
compiles. That’s because std::string
is not a POD. A simple solution to your dilemma is to provide a default constructor for foo
:
class foo { public: foo() { } };
Now your const foo x;
code compiles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With