Monday, 27 June 2016

Can we call the non-volatile member function using the volatile object?

 
Guess the output of the following program.

#include<iostream>

class VolatileClass
{

   public:
      int a;
      void callfunc()
      {
         std::cout<<"Called";
      }
};

int main()
{

   VolatileClass volatile a;
   a.callfunc();

   return 0;
}

Answer:

The above program will not compile because ,

Simple Answer:


Volatile objects  should call only volatile member functions.

Complex Answer:


If object is declared as volatile, then all member function which is called with that object should be declared as volatile

      void callme() volatile
      {
         std::cout<<"Called";
      }

So why it has to be volatile?

Note: Answer is based purely  on my point of view.

In, volatile is keyword which instructs the compiler like “Dear genius, don’t perform any optimization on that object”. Here for all member function this pointer is passed as hidden variable. Since object is declared as volatile, compiler should not perform any optimization on this pointer.

Consider one member function which is declared without volatile

      void callme()
      {
         this->a=1;
                // Perform some other activity.
         this->a=1;  
      }
Since compiler is genius, compile will make two statements “this->a=1;” as one statement because throughout the function value of a is 1. So second statement “this->a=1;” will be removed by the compiler.


Compiler will perform this kind of genius activity when volatile keyword is used in the member function.