?
Solved

19. Why we need constant method? What is the difference of defining constant method of usual method?

Posted on 2015-01-24
2
Medium Priority
?
85 Views
Last Modified: 2015-02-11
19. Why we need constant method? What is the difference of defining constant method of usual method?
0
Comment
Question by:Nusrat Nuriyev
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 40568224
A constant method differes from all other methods by the fact that it is not allowed to make any changes to data members of the class it belongs to. Consider e.g. a method that basically prints out the data - it won't alter it. So that's a ideal candidate for making it 'const' and thus allow not only the compiler to make some optimizations but also make clear to others who might derive from that class that altering any data when overriding this method has to be avoided.
0
 
LVL 86

Accepted Solution

by:
jkr earned 2000 total points
ID: 40568230
Ooops, there is a notable exception - any data declared as 'mutable' can be altered from a const method, e.g.

class MyClass {
public:
    void foo(int x) const {
        std::cout << "this is 'foo()' called with " << x << std::endl;

        value = x; // if 'value' was not mutable, the compiler would throw an error here
    }
protected:
    mutable int value;
};                         
                                          

Open in new window

0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question