As pointed out earlier, the private data of a class can be accessed only through the member functions of that class. The
main()
cannot contain statements that accessnumber
and cost
(of class item
) directly.
However, the member functions which are public, can be accessed from
main()
. The following is the format for calling a public member function:
For example,
The function call statement (in case of class
item
discussed above) is valid and assigns the value 100 to number and 75.6 to cost of the object x by implementing thegetdata()
function. The assignments occur in the actual function.
Similarly, the statement:
would display the values of data members.
Remember, a member function can be invoked only by using an object of the same class. Hence the statement like:
has no meaning.
Similarly, the statement:
is also illegal. This is because although x is an object of the type
item
to which number
belongs, the number
(declared private) can be accessed only through a member function and not by the object directly.
It may be noted that objects communicate by sending and receiving messages. This is achieved through member functions. For example:
sends a message to the object x requesting it to display its contents.
0 comments:
Post a Comment