Prayagasoft - web designer India, Ecommerce developer india, Ecommerce design

Mutable

In C++ it's possible to have a class object instance that is constant and cannot be modified by the program, once initially set up. For example:

class A { public: int x; A(); }; const A a; void g() { a.x = 37; }

is illegal. In a similar way, invoking a non-const member function on a const object is also illegal:

class A { public: int x; A(); void f(); }; const A a; void g() { a.f(); }

The reason for this latter prohibition is due to separate compilation. A::f() may be defined in some other translation unit, and there's no way of knowing whether it modifies the object upon which it operates.

It is possible to define const member functions:

void f() const;

that are allowed to operate on a const object instance. Such a function does not modify the instance it operates on. The type of the "this" pointer for a class T is normally:

T *const this;

meaning that the pointer cannot be changed. Within a const member function, the type is:

const T *const this;

meaning that neither the pointer nor the pointed-at object instance can be modified.

Recently a new feature has been added to C++ to selectively allow for individual data class members to be modified even for a const object instance, and lessen the need for casting away of const. For example:

class A { public: mutable int x; A(); }; const A a; void f() { a.x = 37; }

This says that "x" can be modified even though it's a member of a const object instance.

How useful "mutable" turns out to be remains to be seen. One cited example for its use is within classes whose object instances appear constant but actually do change their state internally. For example:

class Box { double xll, yll; // lower left X,Y double xur, yur; // upper right X,Y double a; // cached area public: double area() const { a = (xur - xll) * (yur - yll); return a; } class Box(double x1, double y1, double x2, double y2) : xll(x1), yll(y1), xur(x2), yur(y2) { } }; const Box b(1.0, 1.0, 11.0, 14.0); void f() { b.area(); }

which is illegal usage unless we instead say:

class Box { double xll, yll; // lower left X,Y double xur, yur; // upper right X,Y mutable double a; // cached area public: double area() const { a = (xur - xll) * (yur - yll); return a; } class Box(double x1, double y1, double x2, double y2) : xll(x1), yll(y1), xur(x2), yur(y2) { } }; const Box b(1.0, 1.0, 11.0, 14.0); void f() { b.area(); }

 

India seo freelance web designer India web development ecommerce website developer India
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100