<p>I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:</p>

<pre><code>struct Widget
{
    Widget():x(0), y(0), z(0){}

    int x, y, z;
};

struct WidgetHolder //Just a simple struct to hold four Widgets.
{
    WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}

    Widget&amp; A;
    Widget&amp; B;
    Widget&amp; C;
    Widget&amp; D;
};

class Test //This class uses four widgets internally, and must provide access to them externally.
{
    public:
        const WidgetHolder AccessWidgets() const
        {
            //This should return our four widgets, but I don't want anyone messing with them.
            return WidgetHolder(A, B, C, D);
        }

        WidgetHolder AccessWidgets()
        {
            //This should return our four widgets, I don't care if they get changed.
            return WidgetHolder(A, B, C, D);
        }

    private:
        Widget A, B, C, D;
};

int main()
{
    const Test unchangeable;

    unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget&amp; be const?
}
</code></pre>

<p>Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.</p>

<p>Can someone explain to me why the code in main() compiles?</p>

<p>Thank you very much.</p>

[{'answer_id': 57364, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 2, 'selected': False, 'text': '<p>unchangeable.AccessWidgets():</p>\n\n<p>At this point, you are creating a new object of type WidgetHolder. \nThis object is not protected by const. </p>\n\n<p>You are also creating new widgets in the WidgetHolder and not references to the Wdiget. </p>\n'}, {'answer_id': 57370, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 2, 'selected': False, 'text': "<p>Your <code>WidgetHolder</code> is going to hold invalid references (pointers). You are passing objects on the stack to the constructor and then holding references to their (temporary) addresses. This is guaranteed to break.</p>\n\n<p><strong>You should only assign references to objects with the same (or greater) lifetime as the reference itself.</strong></p>\n\n<p>Pass references to the constructor if you must hold references. Even better, don't hold the references at all and just make the copies.</p>\n"}, {'answer_id': 57376, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 3, 'selected': True, 'text': "<p>This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder.</p>\n\n<p>The problem appears to lie in this line:</p>\n\n<pre><code>WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}\n</code></pre>\n\n<p>As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to:</p>\n\n<pre><code>WidgetHolder(Widget &amp;a, Widget &amp;b, Widget &amp;c, Widget &amp;d): A(a), B(b), C(c), D(d){}\n</code></pre>\n\n<p>After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution.</p>\n"}, {'answer_id': 57431, 'author': 'Greg Rogers', 'author_id': 5963, 'author_profile': 'https://Stackoverflow.com/users/5963', 'pm_score': 3, 'selected': False, 'text': "<p>You need to create a new type specifically for holding const Widget&amp; objects. Ie:</p>\n\n<pre>\n<code>\nstruct ConstWidgetHolder\n{\n    ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){}\n\n    const Widget& A;\n    const Widget& B;\n    const Widget& C;\n    const Widget& D;\n};\n\nclass Test\n{\npublic:\n    ConstWidgetHolder AccessWidgets() const\n    {\n        return ConstWidgetHolder(A, B, C, D);\n    }\n</code>\n</pre>\n\n<p>You will now get the following error (in gcc 4.3):</p>\n\n<pre>\nwidget.cc: In function 'int main()':\nwidget.cc:51: error: assignment of data-member 'Widget::x' in read-only structure\n</pre>\n\n<p>A similar idiom is used in the standard library with iterators ie:</p>\n\n<pre>\n<code>\nclass vector {\n    iterator begin();\n    const_iterator begin() const;\n</code>\n</pre>\n"}, {'answer_id': 58537, 'author': 'Pieter', 'author_id': 5822, 'author_profile': 'https://Stackoverflow.com/users/5822', 'pm_score': 0, 'selected': False, 'text': '<p>EDIT: he deleted his answer, making me look a bit foolish :)</p>\n\n<p>The answer by Flame is dangerously wrong. His WidgetHolder takes a reference to a value object in the constructor. As soon as the constructor returns, that passed-by-value object will be destroyed and so you\'ll hold a reference to a destroyed object.</p>\n\n<p>A very simple sample app using his code clearly shows this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass Widget\n{\n    int x;\npublic:\n    Widget(int inX) : x(inX){}\n    ~Widget() {\n    std::cout &lt;&lt; "widget " &lt;&lt; static_cast&lt; void*&gt;(this) &lt;&lt; " destroyed" &lt;&lt; std::endl;\n     }\n};\n\nstruct WidgetHolder\n{\n    Widget&amp; A;\n\npublic:\n    WidgetHolder(Widget a): A(a) {}\n\n    const Widget&amp; a() const {\n    std::cout &lt;&lt; "widget " &lt;&lt; static_cast&lt; void*&gt;(&amp;A) &lt;&lt; " used" &lt;&lt; std::endl;\n    return A;\n}\n\n};\n\nint main(char** argv, int argc)\n{\nWidget test(7);\nWidgetHolder  holder(test);\nWidget const &amp; test2 = holder.a();\n\nreturn 0;\n} \n</code></pre>\n\n<p>The output would be something like </p>\n\n<pre>\nwidget 0xbffff7f8 destroyed\nwidget 0xbffff7f8 used\nwidget 0xbffff7f4 destroyed\n</pre>\n\n<p>To avoid this the WidgetHolder constructor should take references to the variables it wants to store as references.</p>\n\n<pre>\nstruct WidgetHolder\n{\n    Widget& A;\n\npublic:\n    WidgetHolder(Widget & a): A(a) {}\n\n  /* ... */\n\n};\n</pre>\n'}, {'answer_id': 62608, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>The original query was how to return the WidgetHolder as const if the containing class was const. C++ uses const as part of the function signature and therefore you can have const and none const versions of the same function. The none const one is called when the instance is none const, and the const one is called when the instance is const. Therefore a solution is to access the widgets in the widget holder by functions, rather than directly. I have create a more simple example below which I believe answers the original question. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nclass Test\n{\npublic:\n  Test(int v){m_v = v;}\n ~Test(){printf("Destruct value = %d\\n",m_v);}\n\n int&amp; GetV(){printf ("None Const returning %d\\n",m_v); return m_v;  }\n\n const int&amp; GetV() const { printf("Const returning %d\\n",m_v); return m_v;}\nprivate:\n  int m_v;\n};\n\nvoid main()\n{\n  // A none const object (or reference) calls the none const functions\n  // in preference to the const\n  Test one(10);\n  int&amp; x = one.GetV();\n  // We can change the member variable via the reference\n  x = 12;\n\n  const Test two(20);\n  // This will call the const version  \n  two.GetV();\n\n  // So the below line will not compile\n  // int&amp; xx = two.GetV();\n\n  // Where as this will compile\n  const int&amp; xx = two.GetV();\n\n  // And then the below line will not compile\n  // xx = 3;\n\n}\n</code></pre>\n\n<p>In terms of the original code, I think it would be easier to have a WidgetHolder as a member of the class Test and then return either a const or none const reference to it, and make the Widgets private members of the holder, and provide a const and none const accessor for each Widget.</p>\n\n<pre><code>class WidgetHolder {\n...\n\nWidget&amp; GetA();\nconst Widget&amp; GetA() const;\n...\n};\n</code></pre>\n\n<p>And then on the main class</p>\n\n<pre><code>class Test {\n...\nWigetHolder&amp; AccessWidgets() { return m_Widgets;}\nconst WidgetHolder&amp;AcessWidgets() const { return m_Widgets;}\n\nprivate:\n  WidgetHolder m_Widgets;\n...\n};\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/57355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3175/']