const class member functions



Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Display some data

To show: The const class member functions





// constant member function

#include <iostream>

using namespace std;


// --- Class declaration -----

class Date


int month;


// we would test the month only...

Date (int mnt, int dy, int yr);

// A write function, so can't be const

void SetMonth(int mnt);

// A read only function declaration

int GetMonth() const;



// --- Class implementation ---





void Date::SetMonth(int mnt)


// Modify the non const member variable data

month = mnt;



// A read only function implementation

int Date::GetMonth() const


// Does not modify anything

return month;



// ----main program----

void main(void)


Date TheDate(7,4,2004);

// non const member function, OK



cout<<"Month of the sample date is "<<TheDate.GetMonth()<<endl;

// another dummy const object...

const Date BirthDate(7,4,1971);

// Then try to modify the const object, NOT OK

// BirthDate.SetMonth(5);

// const member function sending message...


// So, the following shouldn't have the output data...

cout<<"Another silly call, the month is "<<BirthDate.GetMonth()<<endl;



Output example:


Month of the sample date is 11

Another silly call, the month is -858993460

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index