473,811 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Internals of an object

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_cas t<int*>(&minAge nt);

cout << "iVal=" << minAgent.getVal i() << endl; // iVal=1
cout << "jVal=" << minAgent.getVal j() << endl; // jVal=2

cout << "Change values:" << endl;
*minAgentAddr = -23;
*(minAgentAddr+ 1) = -37;

cout << "iVal=" << minAgent.getVal i() << endl; //iVal=-23
cout << "jVal=" << minAgent.getVal j() << endl; //jVal=-37

return 0;
}

For starters, it appears to me that the impetus behind this

int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

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.

Thanks in advance for your time.
Jul 22 '05 #1
5 1694
"ma740988" <ma******@pegas us.cc.ucf.edu> wrote in message
news:a5******** *************** **@posting.goog le.com...
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_cas t<int*>(&minAge nt);

cout << "iVal=" << minAgent.getVal i() << endl; // iVal=1
cout << "jVal=" << minAgent.getVal j() << endl; // jVal=2

cout << "Change values:" << endl;
*minAgentAddr = -23;
*(minAgentAddr+ 1) = -37;

cout << "iVal=" << minAgent.getVal i() << endl; //iVal=-23
cout << "jVal=" << minAgent.getVal j() << endl; //jVal=-37

return 0;
}

For starters, it appears to me that the impetus behind this

int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

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.

<snip>

No, main never calls setVal(). The reinterpret_cas t 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
Jul 22 '05 #2

"ma740988" <ma******@pegas us.cc.ucf.edu> skrev i en meddelelse
news:a5******** *************** **@posting.goog le.com...
I sat through - what should have been a 10 minute discussion where at
issue is the 'security of a class'.
Security in a class is not dealt with in C++ (it is not dealt with in any
other language that i know of, for that matter). The privacy of member
variables and functions is there simply to avoid shooting yourself in the
foot.

[snip]
For starters, it appears to me that the impetus behind this

int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

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?


The purpose of reinterpret_cas t is to tell the compiler that you know better
and should be used rarely if ever. One place where the is okay is where some
object somehow crosses a language barrier (e.g. call-backs in Windows).
Here, the reinterpret_cas t is justified.
[snip]
/Peter
Jul 22 '05 #3
ma******@pegasu s.cc.ucf.edu (ma740988) wrote:
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_cas t<int*>(&minAge nt);
Non-portable (minAgent may have different alignment requirements
to int), and undefined behaviour if it is de-referenced, because
the class may have padding before the first object.

But in the majority of cases, Agent's memory location will
consist of two ints. So &minAgent will be the same address
as &minAgent.iV al , and &minAgent + 1 will be the same
address as &minAgent.jV al. To rely on this behaviour would
be foolish, of course.
int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

I'm unsure of a 'rational' reason to do such a thing and why is 'that'
even allowed?
Your question applies to reinterpret_cas t in general; and the answer
is that, in some cases it is useful (especially, cases where you
have established by other means that nothing undefined is going
to happen). For example in this case, if you want to change
private data in someone else's object , and you know that on
your platform, iVal will always be at the start of the object.
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;


This could be rewritten (recalling that minAgentAddr is an int *):
minAgentAddr[0] = -23;
minAgentAddr[1] = -37;

Clearer?
Jul 22 '05 #4
ol*****@inspire .net.nz (Old Wolf) wrote in message news:<84******* *************** ***@posting.goo gle.com>...
[...]

Non-portable (minAgent may have different alignment requirements
to int), and undefined behaviour if it is de-referenced, because
the class may have padding before the first object.

But in the majority of cases, Agent's memory location will
consist of two ints. So &minAgent will be the same address
as &minAgent.iV al , and &minAgent + 1 will be the same
address as &minAgent.jV al. To rely on this behaviour would
be foolish, of course.
int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

I'm unsure of a 'rational' reason to do such a thing and why is 'that'
even allowed?


Your question applies to reinterpret_cas t in general; and the answer
is that, in some cases it is useful (especially, cases where you
have established by other means that nothing undefined is going
to happen). For example in this case, if you want to change
private data in someone else's object , and you know that on
your platform, iVal will always be at the start of the object.

I suspect 'always be at the start of the object' means, when viewed
from the perspective of minAgentAddr the object has been more or less
'transformed' and as such iVal and jVal are now viewed as:

Some Value Some Address
iVal - xxx 0x......
jVal - xxx 0x......
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;


This could be rewritten (recalling that minAgentAddr is an int *):
minAgentAddr[0] = -23;
minAgentAddr[1] = -37;

Clearer?

Jul 22 '05 #5
Old Wolf <ol*****@inspir e.net.nz> wrote:
int *minAgentAddr = reinterpret_cas t<int*>(&minAge nt);

I'm unsure of a 'rational' reason to do such a thing and why is 'that'
even allowed?
Your question applies to reinterpret_cas t in general; and the answer
is that, in some cases it is useful (especially, cases where you
have established by other means that nothing undefined is going
to happen). For example in this case, if you want to change
private data in someone else's object , and you know that on
your platform, iVal will always be at the start of the object.


I'd let me add something, as a long C++ practicer :)))

The reinterpret_cas t operator should be used ONLY and EXCLUSIVELY to cast
between char* (const char*, if another is also const) and the other type
(in both ways). The C++ standard does not exclude other uses of
reinterpret_cas t, but this is the only use of reinterpret_cas t, which works.
This operator is used ONLY to get access to the internal representation and
to allocate an object in memory, obtained by some "unusual" way.

One of the correct examples of use of reinterpret_cas t is the definition of
std::string in gcc. This string is implemented in such a way that first there
is allocated all memory required to hold all characters of created string,
including reserved space and internal structure:

{{ refs, size } c[0] c[1] c[2] ... c[size] c[size+1] ... c[size+reserved]}

std::string has one and the only field "dat", which is of "char*" type and
points to c[0]. To get access to the private fields (of Rep private class) the
reinterpret_cas t is used:

Rep* rep = reinterpret_cas t<Rep*>( dat ) - 1;

This is portable, safe and correct. The reinterpret_cas t operator is used
to switch between the raw "internal representation" and a "concrete" object
type. Of course, "refs" and "size" are integers.

No casts between two "concrete" type objects are correct for reinterpret_cas t!
--
1 6 1 7 4 4 2 548 g4bc7a4 66z 3xt7w v1y z9p1 120 32
(( Michal "Sektor" Malecki w4 66 64 73 7564 24 5 v 34 4
)) ektor van Skijlen 1 5 5 1 844 a v r z 4
Software engineer, Motorola GSG Poland 1 2 2a 1 4
WARNING: Opinions presented by me on usenet groups are my personal opinions
ONLY and are not connected to the employer.
Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1768
by: ej | last post by:
I'm trying to figure out how to get at some of the internal interpreter state for exception handlers and debug statements in general. I just read through Section 8 of the Python Tutorial. I see how to catch an exception, and specify an optional argument to get ahold of the exception itself. For example: try: {} except Exception, x: print "class of x =", x.__class__
4
2815
by: Niklaus | last post by:
Hi, I would like to know more about casts.What exactly happens when casts are applied to a variable.I know that if an object of type int is applied an cast of float the result would be of type float. 1) What i would like to know is the about the internals when a cast is applied ? Say we have
3
1799
by: Nadav | last post by:
Hi, I am writing a mixed mode application, I have a mixed mode Assembly manipulating a managed byte array, to access this array in unmanaged code I '__pin' the array, As I understand, pining an object guarantee that it will not be collected by the GC ( by increasing it's refcount or so ), Taking that in mind, looking at the code generated by the compiler I can't see anything taking care of the GC refcount... following is the pinned variable...
6
3663
by: MattC | last post by:
I noticed when storing large amounts of information in the StateServer Service that this does not increase in size, the worker process itself seems to grow. I set up a test case to try and prove this, I placed a button on a web form that ran the foloowing code. string temp = "index"; for(int i = 0; i < 1000000; i++) {
9
5759
by: mailtogops | last post by:
Hi, I have this question in mind for many years.. C++ class provides encapsulation which encapsulate its members and member function. class Experiment { private:
8
1995
by: Grizlyk | last post by:
Hello I want to understand the exception habdling in C++ more, because i think no one can apply anything free (free - without remembering large unclear list of rules and exceptions from rules and exceptions from exception from rules) if he does not understand "why" the thing have done excactly as is. I know, some people do not agree with me at the point of "why".
1
1695
by: Jobs Gooogle | last post by:
Skills: .Net VC++ Java C++ Windows Internals Unix Internals Location: Bangalore, Hyderabad, Delhi (NCR), Chennai Experience: 3+ Yrs Hand-On Please forward your profiles to mailto: jobsgooogle@gmail.com Consultant Jobs Gooogle (Nick Name)
18
2718
by: Guru Jois | last post by:
Hai, Can I get some docs or links to learn the C compiler internals from basic to advanced. It must contains good documentation of how compilers allocates memory to variables. Bye Guru Jois
5
1335
by: Larry Bates | last post by:
Peter Anderson wrote: Names are pointers in Python that point to values in memory. Names are "bound" to these values with assignment. Names are NOT buckets where you put values as is the case (or thought process) in other languages. Example: a = list(1,2,3) b = a Now a AND b point to the same list in memory
0
9728
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10402
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10135
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9205
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6890
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3018
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.