2

Is there any way to do this:

class example {
public:
   const int dontModifyMe;

   example() {
      // setup for dontModifyMe..
      dontModifyMe = getValueForDontModifyMe(earlierSetup);
   }
}

example ex;
cout << ex.dontModifyMe; // works
ex.dontModifyMe = 4 // error

If dontModifyMe didn't need setup, I would just use the member initialization list. Is there a way around this that doesn't require explicit getter/setter methods?

7
  • 2
    Why can't you have getter/setters? Jul 21, 2015 at 19:41
  • Not an explicit setter, but a getter is. Jul 21, 2015 at 19:46
  • 1
    Your sample code constructor should not compile.
    – user2249683
    Jul 21, 2015 at 19:48
  • 1
    That member is const, For user-defined construction like yours, it has to be in the member initialization list, so the idea of "I would..." should be "I have to...", and thereby considerably restricts your options if you want to expose a const member directly without a getter. Thus, you have to get creative with your setup function, as it will need to appear as the initialization value for dontModifyMe in the member initializer list if you intend on keeping dontModifyMe as you currently have it declared.
    – WhozCraig
    Jul 21, 2015 at 19:54
  • @LawrenceAiello for semantic reasons. Most members are public, and object.writableValue.nonWritableValue looks better than object.writableValue.getNonWritableValue(). Jul 21, 2015 at 19:57

2 Answers 2

11

Something that I have used in the past is along the lines of:

class example {
    int m_theValue;
public:
    const int &theValue = m_theValue; 
}

This allows you to edit the value internally via m_theValue while keeping a constant interface available in the "public" realm. It is similiar in effect of a getter/setter method, but doesn't require the actual usage of said methods.

2
  • Very interesting. I never would have thought of that. Jul 21, 2015 at 20:01
  • @MichaelHagar Thanks, just something I found a while ago. I think it just makes a slightly more concise and elegant solution. (As compared to a getter/setter method) Jul 21, 2015 at 20:21
2

Example( compiled with gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04) )

using namespace std;

int initializer( int c )
{
    return 4 * c;
}

class A
{
public:
    A() : v( initializer( 5 ) ) {}
    const int v;
};

int main(int argc, char *argv[])
{
    A a;
    cout << "Result " << a.v << endl;

    return 0;
}

Result

Result 20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.