c++volatile

volatile + object combination disallowed in C++?


I'm using an embedded compiler for the TI TMS320F28335, so I'm not sure if this is a general C++ problem (don't have a C++ compiler running on hand) or just my compiler. Putting the following code snippet in my code gives me a compile error:

"build\main.cpp", line 61: error #317: the object has cv-qualifiers that are not
compatible with the member function
        object type is: volatile Foo::Bar

The error goes away when I comment out the initWontWork() function below. What is the error telling me and how can I get around it without having to resort to using static functions that operate on a volatile struct?

struct Foo
{
    struct Bar
    {
        int x;
        void reset() { x = 0; }
        static void doReset(volatile Bar& bar) { bar.x = 0; } 
    } bar;
    volatile Bar& getBar() { return bar; }
    //void initWontWork() { getBar().reset(); }
    void init() { Bar::doReset(getBar()); } 
} foo;

Solution

  • In the same way you cannot do this:

    struct foo
    {
        void bar();
    };
    
    const foo f;
    f.bar(); // error, non-const function with const object
    

    You cannot do this:

    struct baz
    {
        void qax();
    };
    
    volatile baz g;
    g.qax(); // error, non-volatile function with volatile object
    

    You must cv-qualify the functions:

    struct foo
    {
        void bar() const;
    };
    
    struct baz
    {
        void qax() volatile;
    };
    
    const foo f;
    f.bar(); // okay
    
    volatile baz g;
    g.qax(); // okay
    

    So for you:

    void reset() volatile { x = 0; }