constant constructors

Hello. In my program, I am trying to define a constant variable through a constructor, but it returns an error. Do I need to somehow make the constructor a constant? Thanks for answering.

#include <iostream>

using namespace std;

class Objects
{
private:
const int x;
public:
Objects(int);
~Objects();
int getObjects() const { return x; }
};

int main()
{

Objects object1(5);
cout << object1.getObjects() << endl;



return 0;
}

Objects::Objects(int x)
{
this->x = x;
}

Objects::~Objects()
{
}
A const int must be explicitly initialised.

1
2
3
4
5
6
7
8
9
struct object
{
    explicit object( int v ) ;
    const int value ; // const, must be explicitly initialised
};

object::object( int v ) : value(v) // initialise member value
{
}
I think the point here is that it needs to be initialized in the member initializer list of the constructor and not in its body.
Your situation is very similar to what I can do with local variables:
1
2
3
4
const int foo; // warning: uninitialized constant
foo = v; // error: attempt to modify a const

const int bar = v; // ok, proper initialization 

Part of that is probably due to the reuse of '=' in different contexts. One '=' is assignment while the other '=' is initialization.

Analogous:
1
2
3
4
5
6
7
8
9
10
Foo::Foo( int v )
// warning: uninitialized constant
{
  foo = v; // error: attempt to modify a const
}

Bar::Bar( int v )
: bar( v ) // ok, proper initialization
{
}
I think the point here is that it needs to be initialized in the member initializer list of the constructor and not in its body.

Or, to be more precise about it:

If you set the value of a data member in the initialiser list of a constructor, you are initialising that member.

If you set the value of a data member in the body of the constructor, you are not initialising the member. You are creating it as an unitialised member, and then assigning a value to it afterwards. And, if your member is const, that is illegal, because you can only set the value at creation.
Topic archived. No new replies allowed.