Reputation: 105
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?
Upvotes: 4
Views: 3738
Reputation: 3985
Technically you can modify it later (but that is probably not a good idea). After you have thought about it for a good long time look at this code:
const string s = "";
*const_cast<string*>(&s) = "new string";
To use this in your code you could create a parameterless constructor like this:
Customer() : x("") { }
And then modify it later in your code:
*const_cast<string*>(&x) = "new string"
Although this might be a bad idea to do in practice. You should look at this post for more info about the dangers of this
Another alternative to this is to create a cool struct:
template<class T>
class OneTimeAssign{
T data;
bool alreadyAssigned;
public:
OneTimeAssign() : data(), alreadyAssigned(false){ }
void operator=(T&& newData){
if (alreadyAssigned) throw "Error";
data = newData;
alreadyAssigned = true;
}
operator const T&() const{
return data;
}
const T* const operator->(){
return &data;
}
};
You could then use it like this:
OneTimeAssign<std::string> Mine;
Mine = "First assign";
//Mine = "Second assign"; //Runtime Error
std::cout << (std::string)Mine << std::endl;
system("pause");
Upvotes: 0
Reputation: 1
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
.
Upvotes: 3