const member function

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.

sorry for my english
Thanks
Last edited on
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.
No
@jlb
However a non-const member function can be called, provided this function doesn't actually modify the class.


Could you provide a compiled example where a non-const member function is called for a const object of the class type?
Last edited on
closed account (zb0S216C)
jlb wrote:
"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.

Wazzak
Last edited on
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)?

thanks again
Following will return the value of variable hora
int Tiempo::cambiar_hora() { return hora; }

Following will return the refernce of variable hora
int & Tiempo::cambiar_hora() { return hora; }
1
2
3
4
5
6
7
8
9
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
    int const &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.
Last edited on
thanks.
Topic archived. No new replies allowed.