Solved

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

Posted on 2015-01-24
2
70 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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

776 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