Const Member Functions

Const Member Functions

Question:
What does the ‘const’ in the following funciton prototype mean?

class A{public: void fn (int a ) const;}

Answer:
The const after a member function’s parameter list indicates that the function doesn’t change the state of its object. Such a function is also called an “observer function.” The use of const stems from the “design by contract” idiom, whereby a design premise (i.e., the function doesn’t change its object’s state) is enforced by the language. Thus, if you try to change the state of the object through this function, e.g., assign a new value to one of the members, the compiler will issue an error message.

The use of const is important for two reasons: it enables users to call such a function safely (even if they didn’t examine its definition), knowing that it doesn’t change its object’s state behind their back. Secondly, in a well-designed application, the lack of const after the parameter list indicates that the member function may change the state of its object.

A classic example of this dichotomy is the getter and setter functions: a setter is never const because it assigns a value to an object’s member. On the other hand, a getter merely returns an existing value without changing its object. Therefore, it’s declared const.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several