Hi guys, I just want to check if the next statement is correct.
Only const member functions of a class can manipulate or called on const objects of the class, except when initialization of the object in which the constructor is allowed to call non-const member function to initialize the const obsject.
If a class is declared const then you can't change any non-mutable variable after construction. However a non-const member function can be called, provided this function doesn't actually modify the class.
"However a non-const member function can be called, provided this function doesn't actually modify the class."
No. A constant object can only call constant member-functions. However, a constant member-function can modify mutable data-members because "mutable" data-members are excluded from const-checking; hence the ability to modify mutable data-members from a constant member-function.
hi, thanks for the answers.....
I have another I suppose silly question for which I dont want to open up another topic.
I have a class called Tiempo, and that class has a data member of type int called hora. If I use one memebr function of that class that returns hora as following
Tiempo::cambiar_hora(){
( do some operations not relevant for now )
return hora;
}
Am i just returning a copy of the value of hora? or is this an example of returning a reference to a private data member (hora was declared a provate data member)?
class MyClass
{
int x;
public:
int f() { return x; } //only for non-const
int f() const { return x; } //for const (makes above function useless)
int &g() { return x; } //only for non-const, x can be modified externally
intconst &g() const { return x; } //for const, returns const reference (useless for primitives)
};
There are also some quirks involving pointers. If you are interested for all the stuff about const member functions and such, you can look up const-correctness on e.g. wikipedia or google.