Tarique said:
Can someone please explain the idea of Logical Constness as explained in
section 10.2.7.1 Of Stroustrup's "The C++ Programming Language" ,with a
short working code if possible.
Thank You
From - Thu
I have tried implementing the example given in the same section (Naive
though and only to test the idea!)
#include<iostream>
#include<string>
using namespace std;
class Date {
int d,m,y;
bool cache_valid;
string cache;
void compute_cache_value();//fill cache
//..
public:
Date(int dd = 0,int mm = 0,int yy = 0); // Default constructor
static Date default_date;
~Date(){}; // Destructor
string string_rep()const;//string representation
Date& add_day (int n);
};
Date Date::default_date(03,01,2000);
Date:
ate(int dd,int mm,int yy)
{
cache_valid = false;
d = dd ? dd : default_date.d;
m = mm ? mm : default_date.m;
y = yy ? yy : default_date.y;
}
void Date::compute_cache_value()
{
switch(d) //Test_Only
{
case 1:case 8:case 15:case 22:case 29:cache = "Monday"; break;
case 2:case 9:case 16:case 23:case 30:cache = "Tuesday"; break;
case 3:case 10:case 17:case 24:case 31:cache = Wednesday";break;
case 4:case 11:case 18:case 25:cache = "Thursday"; break;
case 5:case 12:case 19:case 26:cache = "Friday"; break;
case 6:case 13:case 20:case 27:cache = "Saturday"; break;
case 7:case 14:case 21:case 28:cache = "Sunday"; break;
}
}
string Date::string_rep() const
{
if(cache_valid == false) {
Date* th = const_cast<Date*>(this);//Cast away const
th->compute_cache_value();
th->cache_valid = true;
}
return cache;
}
/*
According to Stroustrups "The C++ Programming Language",
the const_cast operator is _not guaranteed to work_ when applied to an
object that was originally declared as const.
Why is it so ?
*/
Date& Date::add_day (int n) { //Without any bounds check!
d+=n; //I assume d remains < 31
cache_valid = false;
return *this;
}
int main()
{
Date d1;
const Date d2;
string s1=d1.string_rep();
cout<<s1<<endl;
d1.add_day(2);
cout<<d1.string_rep()<<endl;
string s2=d2.string_rep(); //Undefined Behaviour .Why ?
cout<<s2<<endl;
return 0;
}