[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
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
?
88 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 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

834 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