Ch7 Const Member Functions of a Class
Hello all,
In Beginning Visual C++, Ivor Horton says (on page 361, chapter 7) if we declare an object as
'const', it will have a 'this' pointer that is const, so the compiler
will not allow any class member function to be called that does not
assume the 'this' pointer is const.
In the example below, I haved added 'const' to the 'CBox match' object
in the main function as Ivor suggests in the example, and this did not give me the error I was
expecting from his example. The book says I will get an error at the
class function 'Compare()' unless I make that class function const as
well. But I get the opposite results. Everything is fine if I don't
make the class member function 'Compare' const. When I do make it
const, I get an error at class function 'Volume' (which I sort of
expected - it would need to accept a const pointer too, right?).
Anyhoo, what gives? Why can I declare the object const, but not the
class function that the object later calls from main() and the program still runs (but Ivor's didn't)?? Is it
because the class function 'Compare' doesn't actually modify member
data? If so, any speculation as to why the author got the compiler
error at 'Compare' instead of 'Volume'??
Thanks in advance,
[code]
// Ex7_07.cpp
// Calculating the volume of a box with a member function
#include <iostream>
using std::cout;
using std::endl;
class CBox // Class definition at global
scope
{
public:
// Constructor definition
CBox(double lv=1, double bv=1, double hv=1)
{
cout << endl << "Constructor Called.";
m_Length = lv;
m_Width = bv;
m_Height = hv;
}
// Function to calculate the volume of a box
double Volume()
{
return m_Length*m_Width*m_Height;
}
// Function to compare two boxes which returns true (1)
// if the first is greater than the second, and false (0) if
otherwise
int Compare(CBox xBox)
{
return this->Volume() > xBox.Volume();
}
private:
double m_Length; // Length of box in inches
double m_Width; // Width of box in inches
double m_Height; // Height of box in inches
friend double BoxSurface(CBox aBox);
};
double BoxSurface(CBox aBox)
{
return 2.0*(aBox.m_Length*aBox.m_Width) +
(aBox.m_Length*aBox.m_Height) +
(aBox.m_Height*aBox.m_Width);
}
int main()
{
const CBox match(2.2, 1.1, 0.5);
CBox cigar(8.0,5.0,1.0);
if(cigar.Compare(match))
cout << endl
<< "match is smaller than cigar";
else
cout << endl
<< "match is equal to or larger than cigar";
cout << endl;
return 0;
}
Sincerely,
Brian
__________________
Sincerely,
Brian
|