Solved

MyMethod()const ..question

Posted on 1998-11-27
2
198 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
ID: 1178746
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
ID: 1178747
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone 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

Suggested Solutions

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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…

829 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