473,691 Members | 3,174 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing private member of a class through type-casting

Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;
return 0;
}

I understand that I can not change the private attributes of a class,
but what does standard have to say about the code above?

Apr 7 '06 #1
31 3167

dragoncoder wrote:
Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;
return 0;
}

I understand that I can not change the private attributes of a class,
but what does standard have to say about the code above?


That its behavior is undefined. It might work...it might not...it
might end the world as you know it...undefined.

Apr 7 '06 #2
dragoncoder posted:
Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
You've create an object of the type "A". This object contains within it
an object of the type "int".

int* ptr = (int*)&x;
The expression "&x" is of the type "A*" (leaving out const). You have
used an old C-style cast to turn it into an "int*". This is illegal.

Even if your code was legal, you make the assumption that the address of
"x" is equal to the address of "x.a". I'm not sure if the Standard gives
any such guarantee. If the object was of a class which contained virtual
methods, your code would be even less reliable.
*x = 10;
The value of "x" is undefined, so your the behaviour of the above
statement is undefined.
return 0;
}

-Tomás
Apr 7 '06 #3

dragoncoder wrote:
int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;


Oh, I missed something here. *ptr = 10; would have been undefined. *x
= 10 doesn't compile as A doesn't have an operator*.

BTW, (int*)&x is totally legal. It is a C-style cast and as is the
case with all C-style casts it can do things unexpectedly. What this
resolves to is a reinterpret_cas t<int*>(&x). This is of course legal
but has undefined results. A static_cast would be illegal and using
the C++ casting mechanism would have warned you about the undefined
nature of the cast...this is why C-Style casts are bad.

Apr 7 '06 #4
*x = 10;


I presume that should have been:

*ptr = 10;
-Tomás
Apr 7 '06 #5
Tomás wrote:
dragoncoder posted:
Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
You've create an object of the type "A". This object contains within it
an object of the type "int".

int* ptr = (int*)&x;


The expression "&x" is of the type "A*" (leaving out const). You have
used an old C-style cast to turn it into an "int*". This is illegal.

Not quite illegal, merely undefined.
*x = 10;


The value of "x" is undefined, so your the behaviour of the above
statement is undefined.
return 0;
}

-Tomás

Apr 7 '06 #6
dragoncoder wrote:
Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;
return 0;
}

I understand that I can not change the private attributes of a class,
but what does standard have to say about the code above?


If I turn my car to drive the wrong way up a one-way street, it obeys
me! Hah! Stupid car. Sometimes I will even get where I want to go.

Apr 7 '06 #7

Tomás wrote:
*x = 10;

I presume that should have been:

*ptr = 10;

Yes, i actually meant to write *ptr = 10; Apologies for the same.
-Tomás


Apr 7 '06 #8

Pete C wrote:
dragoncoder wrote:
Consider the code

class A {
private:
int a;
};

int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;
return 0;
}

I understand that I can not change the private attributes of a class,
but what does standard have to say about the code above?


If I turn my car to drive the wrong way up a one-way street, it obeys
me! Hah! Stupid car. Sometimes I will even get where I want to go.


But the result is pretty well defined even if there are a couple
alternative end scenarios. It is also, as apposed to the code in
question, quite illegal.

;)

Apr 7 '06 #9
If I correct the code so that *x = 10 becomes *ptr = 10, even then is
the behaviour undefined ?

I want to know which step I am doing wrong ? Is it illegal to assign
(int*)&x to ptr ? Or is it illegal to do *ptr = 10 ? I am confused. The
corrected is posted again.

class A {
private:
int a;
};

int main(void) {
A x;
int* ptr = (int*)&x;
*ptr = 10;
return 0;
}

Apr 7 '06 #10

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

Similar topics

5
2410
by: Sandeep | last post by:
Hi, In the following code, I wonder how a private member of the class is being accessed. The code compiles well in Visual Studio 6.0. class Sample { private: int x; public:
2
2303
by: Steven T. Hatton | last post by:
I find the surprising. If I derive Rectangle from Point, I can access the members of Point inherited by Rectangle _IF_ they are actually members of a Rectangle. If I have a member of type Point in Rectangle, the compiler tells me Point::x is protected. I would have expected Rectangle to see the protected members of any Point. Compiling the following code give me this error: g++ -o rectangle main.cc main.cc: In member function `size_t...
4
5727
by: Tom | last post by:
Let's say I've got a class defined in a header file. class foo { private: ... int bar; .... }; Now lets say I have a function that needs to access the private variable
4
3035
by: ambar.shome | last post by:
Hi, Please take a look at the code snippet given below:#include<iostream> using namespace std; class A { public: virtual void test(){cout<<"Default implementation called"<<endl;}
8
2738
by: dwok | last post by:
I have been wondering this for a while now. Suppose I have a class that contains some private member variables. How should I access the variables throughout the class? Should I use properties that expose the variables or is it OK to just access the variables directly? Keep in mind that I am talking about accessing the variables from within the class that they are defined. Thanks!
23
2590
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624. I read the description, decided that it's exactly what I want, and ignored the warning. Now I'm trying to inherit using a template. Instead of "destructor could not be generated because a base class destructor is inaccessible", I now have an...
6
5035
by: earthwormgaz | last post by:
Is the following legal? class Outer { class Inner { private: Inner() { } };
2
2597
by: mickey22 | last post by:
Hi all, I have some data members and member functions that are declared as private in a class A. Now I want to use these data members and functions(which are private) in my new C++ source file(.cpp file).I have created pointer to this class A, and tried to use the functions but I am getting an errror that: cannot access private data member. Could anyone please help me with this?Thanks Example : ///abc.cpp file (my source file)
6
1558
by: smoermeli | last post by:
#include <iostream> #include <vector> class Thing { private: int value; friend class Person; public: int getValue() { return value; } void setValue(const int val) { value=val; }
2
1595
by: agendum97 | last post by:
Is there a way of constructing a "class" in JavaScript to access a private member of a different scope of the same type? It is important that the variable remain private, and not accessible in anyway publically. For example: function SomeObj(privateKey) { this.process = function(someObj) { if (!(someObj instanceof SomeObj))
0
8598
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...
0
8951
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8786
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
8793
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...
1
6457
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4322
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...
0
4550
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2965
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
2225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.