How to prevent modification of objects in C++ using volatile2 min read

An object which can be modified by some unknown force (like hardware io) other than the programs itself can be declared as volatile. The compilers doesn’t apply any optimization for such volatile object. The syntax for declaring a volatile objects is as follow:

volatile ClassName object-name;

A member functions can be declared as volatile to make the access to members variable to be volatile. A volatile object can access only volatile function. The syntax for creating a volatile functions is as follows:

return-type function-name(args) volatile;

Following programs demonstrates both volatile objects and volatile program:

The output of the above program is as follows:

In the above programs volatile function is ­get_name() and volatile object is s2. The object s2 can access only volatile members function.

A friend class is a class which can access the private and protected member of another classes. If a class B has to be declared as a friend of classes A, it is done as follow:

Following are properties of a friend classes:

  • A class can be a friend of any numbers of class.
  • When class A becomes the friend of class B, class A can access all the members of class B. But class B can access only the public member of class A.
  • Friendship is not transitives. That means a friend of the friend is not a friends unless specified explicitly.

Following program demonstrates a friend classes:

Output for the above programs is as follow:

In the above program class Ba has been declared as a friend of classes Ab. That is why it is able to access private members x of class Ab.

Take your time to comment on this article.

Leave a Comment