You get a bonus - 1 coin for daily activity. Now you have 1 coin

1.4.3. Constant Function Components

Lecture



Class member functions can be described as const. In this case, they cannot change the values ​​of the data members of the class and can return a pointer or reference only to the data members of the class described as const . They are the only functions that can be called on a constant object.

For example, in the conplex class:

class complex {
double re, im;
public:
// ...
double real () const {return re;}
double imag () const {return im;}
};

Declaring the functions real () and mag () as const ensures that they do not change the state of the complex object. The compiler will detect random attempts to violate this condition. When a constant function is defined outside the class, it is necessary to specify const: double complex :: real () const {return re:} A constant member function can be called for both a constant and non-constant objects, while as a non-constant member function, you can call only on an object that is not a constant.

created: 2015-12-20
updated: 2026-03-09
245



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "C ++ (C plus plus)"

Terms: C ++ (C plus plus)