Design question involving casting away constness
Hello Group,
There is some legacy code that i have to make changes to and for which
i need your suggestions.
I am told some technical architect has written this code for some sort
of an UMTS class (a fat interface IMHO) with 250+ methods and 50+
members; and i am not supposed to touch it (nor do i fully understand
it in the first place!).
The simlplifed version with the crux of the problem looks like
this ...
// start snip
class A{
public:
void func() { // does some useful calculation }
void func() const { // left blank, notoriously?? }
};
// here is one of the methods with following semantics
void doCalc(const A& umtsObjIN) {
// here i need to do some useful calculation via the class A's
members
}
// end snip
Since, the const version of the member-functions are undefined, i have
to call the non-const version; somehow from doCalc(...). Three
approaches that i can envision right now ...
1. const_cast<A*>(&umtsObjIN)->func();
2. ((A)umtsObjIn).func(); // 'C' style
3. Make a copy of umtsObjIn into a non-const temporary object and then
invoke the func.
A copyofA = untsObjIN; copyofA.func();
Options 1 and 2, i think are UB** in C++ because the the object that
is passed as argument is instantiated as 'const A aObj;' during
application initialization. (** casting away constness of an object
which was originally defined as const) or is it O.K.?
Option-3 works. There are many such methods called many times! Clearly
in this situation, using option-3 everytime doCalc is called is
costly; but is it the only way?
I tried something like this ..
// start-snip
// i touched class A, breaking the rules and added a virtual method
but,
// i do not wish to touch the original author's methods here.
class A{
public:
// rest of the stuff
virtual void adaptFunc(); // override this
};
class B : public A {
public:
void adaptFunc() {
A::func();
}
};
// end-snip
But dosen't work as it breaks the 'const' contract of 'this' pointer.
Any suggestions from u folks here? May be some sort of an adapter
class?
Or should i start looking for that technical architect :-)
Thanks in advance
Abhay
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]