Consider the following example:
#include <iostream>
class C {
int intArray[2] { 1, 2 };
int *firstElementPt;
public:
int getFirstElement() volatile {
firstElementPt = intArray;
return *firstElementPt;
};
};
int main()
{
volatile C c;
std::cout << c.getFirstElement();
}
This gives me the following compilation error:
In member function 'int C::getFirstElement() volatile':
10:28: error: invalid conversion from 'volatile int*' to 'int*' [-fpermissive]
I'm new to C++. I read that declaring an instance as volatile would implicitly make all it's member variables volatile. And I read that declaring a member function as volatile would mean to mark the hidden *this
pointer as volatile. So why is the assignment firstElementPt = intArray;
still not allowed and leads to error: invalid conversion from 'volatile int*' to 'int*'
?
Volatility and constness do not propagate through pointers, but they do propagate through arrays. So in a volatile instance of the class, firstElementPt
is itself volatile, but the thing it points to is not. The intArray
elements however are volatile. You are attempting to point a volatile-pointer-to-a-non-volatile-int to a volatile int
. This is not allowed.