Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor with constant members

I have a class in C++, say "Customer", and I want to have a member of it for ID,

private:
const string x; // Customer's ID

now the normal constructor would look like this:

Customer::Customer(const string& ID): x(ID){}

Now, I want to build a default constructor, without initializing x. Is it possible? Because if I initialize it to some random value, say "untitled" then I can't change it anymore because its a const.

So should I not build a default constructor at all, or is there a possibility of building one that doesn't initialize x and you can do that later?

like image 623
michael kova Avatar asked Oct 20 '25 18:10

michael kova


1 Answers

Now, I want to build a default constructor, without initializing x. Is it possible?

No, it's not possible.

Because if I initialize it to some random value, say "untitled" then I can't change it anymore because its a const.

That's exactly the purpose of const.

So should I not build a default constructor at all, or is there a possibility of building one that doesn't initialize x and you can do that later?

Well, if x really should be const (which I doubt is actually needed), you shouldn't provide a default constructor, unless you could manage to initialize x uniquely from some constexpr.

like image 80
πάντα ῥεῖ Avatar answered Oct 22 '25 06:10

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!