Reputation:
I have a class called class Car
, which has be instantiated as the object Car car1
. One of the member variables of Car is Car::width
, but when I try to execute the line
cout << car1.width << endl;
from main()
I am told that this is not possible because Car::width
is private. It was my understanding that private members could be accessed by the objects of the class to which they belong, but this situation has me completely stumped. What's the deal with private members being accesses by their own objects?
Upvotes: 4
Views: 5164
Reputation: 54178
If the accessing function (main
in this case) is not a member or friend
of your class Car
, then the compiler is correct in saying that private
member width
is off-limits in this context.
When you think about it, if anybody who could create a Car
could access its private
members, privacy would not mean very much. You make the constructor public
to allow creation of the object, but hide the created object's data members from such users to properly encapsulate them. You limit the manipulation of the class's private
internals to what's allowed by legal usage of the class's public
or protected
members.
Upvotes: 2
Reputation: 101494
cout << car1.width
This isn't car1
trying to get to width
-- it's cout
trying to get to width
. cout
isn't a member of car1
so since width
is private, it fails.
Upvotes: -1
Reputation: 57278
A method on class Car can access the width
member, but your code (the one doing the cout
) cannot.
Upvotes: 0
Reputation: 393
It can be accessed from within a member function, not outside like you have it here. The whole point of a private variable is to prevent exactly what you are trying to do, namely disallow users of the class to use the member variable.
Upvotes: 2
Reputation: 12951
Car
can access width
. But in your example it's you who's trying to access width
. This is exactly the meaning of private
.
Upvotes: 2
Reputation: 24584
Private members are accessible by the methods of the same class to which they belong.
Upvotes: 6