Search code examples
c++classobjectoperator-overloadingvolatile

How to overload operators in C++ when declaring an Object as volatile


I need advice on volatile Objects. Here is my class

class A
{
private:
volatile unsigned long count;
public:

A & operator = (unsigned long number) { count = number; return *this; }
};

I create a instance of the class declared as volatile

volatile A myClass;

When I use the "=" operator to assign a value I get a compiler error

myClass = 5;

How do I have to cast the "this" pointer for this to work? Or is this even the problem?


Solution

  • The first problem is that you cannot call a non-volatile member function using a volatile pointer, reference or instance. This works like const, where you can only call const member functions if your object is const or if your pointer or reference is to a const qualified type. Must must therefor make your member function volatile.

    The second problem is that, since your member function will be made volatile, the this pointer will also be volatile, meaning *this is a volatile A &. You will not be able to bind *this to A &, which is the return type of your operator, because volatile A & cannot bind to A &. Again, this is just like const where you couldn't bind const A & to A &. The solution is to change the return type of your operator to volatile A &.

    Your operator should look like this :

    volatile A & operator= (unsigned long number) volatile
    {
        count = number; 
        return *this; 
    }