Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 223
msc Avatar asked Aug 01 '17 11:08

msc


2 Answers

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;
}
like image 138
songyuanyao Avatar answered Oct 15 '22 10:10

songyuanyao


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.

like image 33
StoryTeller - Unslander Monica Avatar answered Oct 15 '22 10:10

StoryTeller - Unslander Monica