tags:

views:

70

answers:

4

What does it actually mean when you declare a variable 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?

A: 

Other than accesability there is no difference!

Mario The Spoon
A: 

public and private are there only until compilation of the code. They don't have anything to do with the runtime or memory management.

Naveen
+3  A: 

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..

liaK
+2  A: 

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.

jalf
Thanks for the clarification. I just assumed that declaring a variable private would make it secure.
tsudot