Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a const instance of a class

Tags:

c++

constants

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...

like image 645
Nim Avatar asked Jan 12 '11 21:01

Nim


People also ask

Where do you instantiate a const field in a class?

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.

How do you declare a const object in C++?

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.

How do you declare a const variable in a class typescript?

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.

How do you declare and initialize a constant in C++?

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 .


1 Answers

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.

like image 102
Konrad Rudolph Avatar answered Oct 12 '22 15:10

Konrad Rudolph