Constant Objects

#include <iostream.h>
/*********************************************************************
 File: constobject.C
 This program demonstrates errors generated when a non-const function
 attempts to modify a const object.  NOTE the constructor for the
 object need not be declared as const function.  This also applies to
 destructors.  
******************************************************************/

class date {
     int day;
     int month;
     int year;
public:
     date();
     void set_date(); // THIS FUNCTION CAN MODIFY THE OBJECT
     void print() const; // THIS FUNCTION CANNOT MODIFY THE OBJECT
};

date::date()
{
     cout << "Constructing..." << endl;
     day   = 9;
     month = 9;
     year  = 1997;
}

void date::set_date()
{
     int d, m, y;
     cout << "Enter date in DD MM YY format: ";
     cin >> d >> m >> y;
     day = d;
     month = m;
     year = y; 
}

void date::print() const // THE const KEYWORD IS ALSO REQUIRED HERE
{
     cout << "The date stored in this object is:" << endl;
     cout << "Day: " << day << endl;
     cout << "Month: " << month << endl;
     cout << "Year: " << year << endl;
}

typedef date Date;

int main()
{
     const Date today; // Unmodifiable object

         today.print();
	 today.set_date(); // This will cause compiler errors

     exit(0);
}

Output:

g++ constobject.C
constobject.C: In function `int main()':
constobject.C:51: call to non-const method `void date::set_date()' with
const object



Back to Previous Page

Document:
Local Date:
Last Modified On: