6

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?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Chethan
  • 905
  • 1
  • 10
  • 18

3 Answers3

5

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.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
4

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

The volatile qualifier works much in the same way as const works. To see what can be done thanks to this, take a look at this Alexandrescu article. That article should also give you some insight into the why.

Andrea Bergia
  • 5,502
  • 1
  • 23
  • 38
  • it is a 2001 article and all I read now is people advising against volatile for critical section/multithreaded purposes and prefer to use mutexes. For instance: https://www.securecoding.cert.org/confluence/display/seccode/POS03-C.+Do+not+use+volatile+as+a+synchronization+primitive – Nikko Nov 08 '11 at 10:37
  • @Nikko: It seems you didn't read more than the title of the article referenced in the answer. Read the *full* article. – Yakov Galka Nov 08 '11 at 11:31