"ma740988" <ma740988@pegasus.cc.ucf.edu> wrote in message
news:a5ae824.0409111949.22c9ac16@posting.google.co m...[color=blue]
> I sat through - what should have been a 10 minute discussion where at
> issue is the 'security of a class'. Truth is I was puzzled by the
> soruce, so much so that I lost track of the end result. In any event,
> consider
>
> #include <iostream>
> using namespace std;
>
> class Agent
> {
> private:
> int iVal;
> int jVal;
> public:
> Agent():iVal(1),jVal(2){}
> void setVal(int newVal) { iVal = newVal; }
> int getVali() const { return iVal; }
> int getValj() const { return jVal; }
> };
>
> class MinAgent : private Agent
> {
> public:
> int getVali() const { return Agent::getVali(); }
> int getValj() const { return Agent::getValj(); }
> };
>
> int main(void)
> {
> MinAgent minAgent;
> int *minAgentAddr = reinterpret_cast<int*>(&minAgent);
>
> cout << "iVal=" << minAgent.getVali() << endl; // iVal=1
> cout << "jVal=" << minAgent.getValj() << endl; // jVal=2
>
> cout << "Change values:" << endl;
> *minAgentAddr = -23;
> *(minAgentAddr+1) = -37;
>
> cout << "iVal=" << minAgent.getVali() << endl; //iVal=-23
> cout << "jVal=" << minAgent.getValj() << endl; //jVal=-37
>
> return 0;
> }
>
> For starters, it appears to me that the impetus behind this
>
> int *minAgentAddr = reinterpret_cast<int*>(&minAgent);
>
> is to fiddle with the internals of the object which puzzled me since
> I'm unsure of a 'rational' reason to do such a thing and why is 'that'
> even allowed?
>
> Pictorially, I'm not following the deferencing of the 'object' and the
> subsequent result. I understand the basic premise behind deferencing
> pointers to change the contents of an address, but from an "object'
> perspective these puzzle me.
>
> *minAgentAddr = -23;
> *(minAgentAddr+1) = -37;
>
> So I tried to step through the source but Visual Studio didn't do me a
> whole lot of justice so I thought:
> minAgentAddr 'calls' function setVal which in turn sets iVal but that
> makes no sense since minAgentAddr + 1 calls what? I'm confused.[/color]
<snip>
No, main never calls setVal(). The reinterpret_cast is accessing and
modifying the internals of the class via low-level (and non-portable) means.
Such code is ugly, tricky, and best avoided.
Sutter wrote a good GOTW about accessing an object's private members
(
http://www.gotw.ca/gotw/076.htm). The example called "the cheat" is the
one that best resembles the code you provided.
--
David Hilsee