5

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;
}
msc
  • 33,420
  • 29
  • 119
  • 214
  • 2
    It will be called normally. – n. m. could be an AI Aug 01 '17 at 11:09
  • Nice phrasing to avoid [this](https://stackoverflow.com/questions/4826719/c-volatile-member-functions), [this](https://stackoverflow.com/questions/16746070/what-does-it-mean-when-a-member-function-is-volatile), and [this](https://stackoverflow.com/questions/2444734/what-is-the-purpose-of-a-volatile-member-function-in-c) being an exact dupe. – StoryTeller - Unslander Monica Aug 01 '17 at 11:46

2 Answers2

7

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;
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
4

You can call it just like a const function on a non-const object, but for different reasons.

The volatile qualifier makes the implicit this parameter be treated as a pointer to a volatile object.

Essentially, this means that the semantics of volatile objects will be applied when accessing the data member(s) of the object. Any read of x cannot be optimized away, even if the compiler can prove there is no recent write after the last read.

Naturally, if the object isn't really volatile the body of func is still correct, albeit not as optimized as it can be. So you can call it just fine.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458