const: Const is C++ version of final in Java. Const can be used at many places.
- const variable
- any variable be it global, local, or in class if declared const becomes un-modifiable
- const member function
- Method in a class declared as const cannot modify variable inside
- Declaration: void display() const; // remember const is after the brackets
- Definition: void classname::display() const { ... }
- const object
- Can't modify any of the data member except ones declared as mutable
- Can call only const methods as they are the only ones guaranteed not to modify object state
Use it often. Makes code more safer.
Example:
const char* name = "shreyas"; // string is constant pointer is not (read R to L)
name = "dhara";
*name = 'S' // Error
char const *location = "hyderabad"; // same as above
char * const weather = "hot"; // pointer is constant string is not
weather = "cool"; // Error
*weather = 'H';
const char * const weather = "hot"; // Both pointer and string it points to are constant
weather = "cool"; // Error
*weather = 'H'; // Error
Coonst and reference: If variable is declared const it's reference must also be declare const. Vice versa is not true
Example:
const int i = 10;
const int &ref = i;
int &err = i; // gives error
int j = 20;
const int &cref = j;
Note. if you return const string like "hello" your method declaration should be
const char* getname() {
return "hello";
return "hello";
}
mutable: Mutable let's you modify the member of const object. By definition const object is non-modifiable and you can only call const methods on them. By setting it mutable you can modify member variable of const object.
Example:
namespace: It is similar to java's package.
class Sample {
private:
mutable int num;
public:
// It is ironic that we have to declare method as const
// that actually modifies the variable
void setNum(int n) const {
num = n;
}
};
...
Sample s;
s.setNum(20);
namespace: It is similar to java's package.
Example:
namespace sample {
// Nested namespace is allowed
namespace nested {
}
class Base {
};
void display();
} // namespace sample
// Definition outside namespace
void sample::display() {
cout << "outside namespace";
}
// We can give alternate name to a namespace
namespace very_very_long_namespace {
class Trial {
};
}
namespace vvln = very_very_long_namespace;
int main() {
sample::Base base;
// Alternate way
using namespace sample;
Base base;
// Error cannot have namespace at global level
// namespce local {
// }
}
No comments:
Post a Comment