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;
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With