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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include<iostream> using namespace std; class Students { private: string names; string regdnos; int ages; string branches; public: void set_names(string); void get_names(Students) volatile; }; void Students::set_names(string n) { names = n; } void Students::get_name(Students s) volatile { cout << "Names is: " << s.name; } int main() { Students s1; s1.set_names("Maheshs"); volatile Student s2; s2.get_names(s1); return 0; } |
The output of the above program is as follows:
1 2 3 | Name is: Maheshs |
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:
1 2 3 4 5 6 7 8 | class A { friend class B; ... ... }; |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include<iostream> using namespace std; class Ab { friend class Ba; private: int xs; public: void set_xs(int n) { xs = n; } }; class Ba { private: int ys; public: void set_ys(int n) { ys = n; } void show(Ab obj) { cout << "xs = " << obj.x << endl; cout << "ys = " << y; } }; int main() { As a; a.set_xs(10); Bs b; b.set_ys(20); b.shows(a); return 0; } |
Output for the above programs is as follow:
1 2 3 4 | x = 10s y = 20s |
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.