Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't a volatile object call nonvolatile member function

Why can't a volatile object call a non-volatile member function?

In case of const, it makes sense that calling a non-const member function violates the constness of the the object and hence it is prohibited. But why in the case of volatile?

like image 907
Chethan Avatar asked Nov 08 '11 10:11

Chethan


2 Answers

In case of const, it makes sense that calling a non-const member function violates the const-ness of the the object and hence it is prohibited. But why in the case of volatile?

It's just the same for volatile. Volatile means every access to an object is a visible side effect and cannot be eliminated. If you called a nonvolatile method on a volatile object, you would violate this property (because the nonvolatile method would treat the object just as a normal object). Therefore, it is impossible.

like image 95
jpalecek Avatar answered Sep 19 '22 00:09

jpalecek


From the standard:

7.1.5.1. If an attempt is made to refer to an object defined with a volatile-quailified type through the use of an lvalue with a non-volatile-quailified type, the program behaviour is undefined.

I'm guessing your compiler posts an error to prevent undefined behavior. The standard stating so should be reason enough.

like image 37
Luchian Grigore Avatar answered Sep 22 '22 00:09

Luchian Grigore