Вы находитесь на странице: 1из 13

CONST AND VOLATILE FUNCTIONS

CONSTANT FUNCTIONS

#include<iostream.h> #include<conio.h> class sample { public: int a; void disp() { cout<<++a; } };

void main() { clrscr(); sample s; s.a=10; s.disp(); getch(); }

OUTPUT:11

Member function does not alter any data in

the class.
The keyword const is placed between the

argument list and the body of the function.


Syntax:

<return type> <function name> (argument 1,argument 2,.) const { <the function body> }

#include<iostream.h> #include<conio.h> class sample { public: int a; void disp() const { cout<<++a; } };

void main() { clrscr(); sample s; s.a=10; s.disp(); getch(); }

ERROR DISPLAYED : CANNOT MODIFY A CONST OBJECT

MUTABLE DATA MEMBERS

Data members cannot be modified by the const function. If a data member is declared as mutable the it can be even modified by const function.
Syntax:
mutable data_type variable_name; mutable int a;

#include<iostream.h> #include<conio.h> class sample { public: mutable int a; void disp() const { cout<<++a; } };

void main() { clrscr(); sample s; s.a=10; s.disp(); getch(); }

VOLATILE FUNCTIONS

A member function can be declared

as volatile if it is

invoked by volatile object.


Volatile objects value can be changed by external

parameters which are not under the control of the program.


Example:

An object taking input from NIC does not take input from our program .As and when hardware interrupts the value related to change without our programs knowledge.

class B { int x; public: void f() volatile; // volatile member function }; void main() { volatile B b; // b is a volatile object b.f(); // call a volatile member function safely }

Вам также может понравиться