This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Can a member variable be declared const in a class without initialization?

Note: This was originally posted on 5th January 2010 at http://forums.arm.com

I am trying to define a class providing an interface to hardware registers. Some of the registers are read-only. I would like to declare these registers const so they cannot be written, but the compiler is insisting I initialize them. But by initializing them, it is guranteed they will be written.

Does anyone have a solution to this dilemma?

Thanks.

Sincerely,
Steve.
Parents
  • Note: This was originally posted on 5th January 2010 at http://forums.arm.com

    Are you intentionally using a C++ compiler; the following is legal C:

    typedef volatile struct device_s {
      int rw;
      const int ro;
    } device_t;

    device_t *dev = (device_t*)0xA0000000;

    void bar(void)
    {
      dev->rw = dev->ro;
      dev->rw = dev->ro;
     
      //  dev->ro = 3; // would generate error
    }


    hth
    s.
Reply
  • Note: This was originally posted on 5th January 2010 at http://forums.arm.com

    Are you intentionally using a C++ compiler; the following is legal C:

    typedef volatile struct device_s {
      int rw;
      const int ro;
    } device_t;

    device_t *dev = (device_t*)0xA0000000;

    void bar(void)
    {
      dev->rw = dev->ro;
      dev->rw = dev->ro;
     
      //  dev->ro = 3; // would generate error
    }


    hth
    s.
Children
No data