A member function can always access the data in __________ , (in C++).
2017
A member function can always access the data in __________ , (in C++).
- A.
the class of which it is member
- B.
the object of which it is a member
- C.
the public part of its class
- D.
the private part of its class
Attempted by 423 students.
Show answer & explanation
Correct answer: B
Concept: A member function is declared as a member of its CLASS, and an ordinary (non-static) member function is invoked ON a specific object; through the implicit this pointer it can access the data members that object holds for its class — the private ones as well as the public ones. Encapsulation hides those members from code OUTSIDE the class, but a member function, being inside the class, can always reach the object it is working on. (A static member function is the exception — it has no this and no bound object — so, by the standard textbook convention, the item means an ordinary member function.)
Application: The blank names where a member function can always access the data. That place is the object it operates on — “the object of which it is a member,” in the item’s wording — because the object holds the private and public data members declared in its class. Consider a class with a private field and a public field:
class Account {
double balance; // private
public:
int id; // public
void show() {
cout << balance << id; // reads BOTH members of THIS object
}
};When show() runs on an Account object it can read that object’s private balance and its public id alike, because a member function can access the data the object holds for its own class.
Why not the others:
the class of which it is member — a member function does belong to its class, but the phrase asks about the DATA: instance data lives in the object at run time, while the class itself only defines the layout, so it is not where the data is accessed.
the public part of its class — too narrow: from inside the class the member function also reaches the private and protected data of its object, not only the public members.
the private part of its class — too narrow in the other direction: it leaves out the public (and protected) members the same function can equally read.
Answer: the object of which it is a member.