Search code examples
c++c++11volatilemember-functions

Calling volatile member function using not volatile object in C++


What happens, If calling volatile member function using not volatile object?

#include <iostream>
using namespace std;

class A 
{
private:
    int x;
public:
    void func(int a) volatile //volatile function
    {
        x = a;
        cout<<x<<endl;
    }
};

int main() 
{
    A a1; // non volatile object
    a1.func(10);
    return 0;
}

Solution

  • The rule is same as const member function. A volatile member function could be called on a non-volatile object, but a non-volatile member function couldn't be called on a volatile object.

    For your case, A::func() will be invoked fine. If you make them opposite, the compilation would fail.

    class A 
    {
    private:
        int x;
    public:
        void func(int a) // non-volatile member function
        {
            x = a;
            cout<<x<<endl;
        }
    };
    
    int main() 
    {
        volatile A a1;   // volatile object
        a1.func(10);     // fail
        return 0;
    }