Solved

MyMethod()const ..question

Posted on 1998-11-27
2
184 Views
Last Modified: 2010-04-01
suppose I have two classes with a const method in the
derived class:
class A
{
 int m_nX;
};
class B : public A
{
 int m_nY;
 int GetValue() const
 { return m_nY; }
};
in this case everthing is allright.
the question: is it legal/proper to do something like
class B : public A
{
 int m_nY;
 int GetValue() const
 {
  m_nX = 4;
  return m_nY;
 }
};
concerning the const method "GetValue()" ???
0
Comment
Question by:nil_dib
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 80 total points
Comment Utility
Assuming that m_nX is a mebmer of 'B', this statement is not legal, as functions that are declared 'const' may not alter _any_ member variable (the compiler will also complain ;-).
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
Note that on compilers that support it, the m_nX member could be declared mutable.  mutable members may be changed from const functions.  However, indiscriminate use of "mutable" discouraged

Note also that m_nX is a private member of the base class.  Thus the error you will get is that m_nX is undefined, not that it is constant.  If it were made public or protected, then you would get the error that it is constant.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
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 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…

728 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

9 Experts available now in Live!

Get 1:1 Help Now