Solved

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

Posted on 2015-01-24
2
60 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
  • 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 500 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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now