Private data types and member functions
What does it actually mean when you declare a variabl开发者_JS百科e or a member function as private in a C++ class? Besides the obvious fact that, these are accessible only by the member functions, How are they mapped differently on memory, than their public counterparts?
From standard docs, 9.2.12,
Nonstatic data members of a (non-union) class with the same access control (clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
The standards has specs for the order of allocation of memory but there isn't much difference in the memory that is being allocated for a public
data member and it's private
counterpart..
Imagine that they were only acessible from member functions, then code like this would break:
class Foo {
int x; // this is private
public:
int& X() { return x; } // this is public, but returns a reference to a private variable
};
Foo foo;
foo.X() = 42; // look, I can set the value of a private member without being inside a member function
In short, one of the most common way to define get/setters in C++ would break if there was some sort of magic enforcing that a private variable must only be accessed by member functions. That's obviously no good.
public
and private
are there to help the programmer structure his code, and nothing more. They offer absolutely no security, and no runtime protection against code accessing a "private" member. Variables are only private in the source code. In the compiled code, there is no difference.
class priva
{
int x=10;
public:
int pub;
};
main()
{
priva a;
int *ptr;
ptr=&a.pub;
--ptr;//4 bite be4 there will be private data
cout<<"Private data having value of 10 is "<<endl;
cout<<*ptr;
}
Other than accesability there is no difference!
public
and private
are there only until compilation of the code. They don't have anything to do with the runtime or memory management.
精彩评论