template boy
template boy

Reputation: 10490

Are private class variables instantiated for each instance of a class?

When I define a variable in a class, every time I declare an instance of this class it creates, in memory, a new copy of that variable for the particular instance. I understand this, but does this hold for when all the member variables are private? For example:

class A {
    int a, b, c;
};

A a;

When I create a new instance, are these private variables still allocated for a even though they can't be used outside the class?

Upvotes: 0

Views: 161

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320747

Your assumption that private variables "can't be used from outside of the class" is incorrect. Declaring a member private simply means that it can't be directly referred by name from outside of the class (except by class friends, of course). "Can't be used" is a much stronger assertion, that happens to be untrue.

If the "outside world" somehow obtains an alternative way to access that private member, it can do that without any restrictions. For example, your class might implement a public access member function that returns a reference (or pointer) bound to the private member. That will make that specific member indirectly accessible from the outside.

In reality there's absolutely no difference between public and private members of the class, aside from the purely conceptual compile-time access restrictions that work at the level of member names. It is a very thin layer of protection implemented at the compiler level. There's nothing physical behind it, i.e. there's no physical difference between data members of the class, regardless of their protection level.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258648

No. Memory allocation is an implementation detail. Consider the code:

class A {
    int a, b, c;
};

int main()
{
   A a;
}

There will probably be no memory allocation whatsoever, because C++ operates on an as-if model. Meaning, if the output is the same as the expected one, the compiler is free to do anything. Including optimizing out dead code.

Typically, though, yes, you can assume space is allocated for all members of an object.

Upvotes: 2

Related Questions