Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does C++ not have a const constructor?
    primarykey
    data
    text
    <p>(<em>Edit: Heavy change because previous example was flawed, which may make some answers/comments seem odd)</em></p> <p>This might be an overly contrived, but the following is legal because of lack of const constructor:</p> <pre><code> class Cheater { public: Cheater(int avalue) : cheaterPtr(this) //conceptually odd legality in const Cheater ctor , value(avalue) {} Cheater&amp; getCheaterPtr() const {return *cheaterPtr;} int value; private: Cheater * cheaterPtr; }; int main() { const Cheater cheater(7); //Initialize the value to 7 cheater.value = 4; //good, illegal cheater.getCheaterPtr().value = 4; //oops, legal return 0; } </code></pre> <p>It seems like providing a const constructor a thing would be as easy technically as const methods, and be analogous to a const overload.</p> <p><em>Note: I'm not looking for '<code>Image( const Data &amp; data ) const</code>' but rather '<code>const Image( const Data &amp; data) const</code>'</em></p> <p>So:</p> <ul> <li>Why is the const constructor absent in C++?</li> </ul> <p>Here's some related material for context:</p> <ul> <li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm</a></li> <li><a href="https://stackoverflow.com/questions/1699307/how-to-deal-with-initialization-of-non-const-member-in-const-object/6936079#6936079">How to deal with initialization of non-const reference member in const object?</a></li> <li><a href="https://stackoverflow.com/questions/5656664/c-classes-const-and-strange-syntax">C++, Classes, Const, and strange syntax</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload