3 ms·
What would be the utility of such a constructor? You can just initialize const objects with regular constructors. How are these objects not "true" const?
by leni536 7y ago
What would be the utility of such a constructor? You can just initialize const objects with regular constructors. How are these objects not "true" const?
- saagarjha 7y agoThe specific use case I had in mind was a implicit “conversion” constructor that took an immutable object and gave back something that you couldn’t strip the const off of (it’d also take a mutable object and give you a normal thing back). What I have specifically is a class that provides a base set of operations and a subclass that lets you do some modifications, and what I am trying to do is wrap it in C++ with an object that is const depending on which class I am converting (converting object to const wrapper_class and mutable_object, a subclass of object, to just wrapper_class).
- leni536 7y agoI don't fully grasp what you are trying to do here. This looks familiar though: > What I have specifically is a class that provides a base set of operations and a subclass that lets you do some modifications If you actually do this with public inheritance then you possibly break const correctness. Having to separate types for the immutable and mutable data structures with appropriate conversions is a sound idea though.
- munchbunny 7y ago> What I have specifically is a class that provides a base set of operations and a subclass that lets you do some modifications Your object isn't actually immutable, it just doesn't let you directly mutate it. That's a really important distinction. That's a common pattern. In C++, rather than using a subclass for the mutator, use a different (friend) class. The semantics for implicit conversion between two different classes will allow you to accomplish what you are asking for with enforcing no changes from one interface but not the other.
- saagarjha 7y ago> In C++, rather than using a subclass for the mutator, use a different (friend) class. Unfortunately I don't control this class :(