Accessing Class Members in C++

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 access number 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:

object-name.function-name(actual arguments);

For example,

x.getdata(100,75.6);

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 the getdata() function. The assignments occur in the actual function.

Similarly, the statement:

x.putdata()

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:

getdata(100, 78.9);

has no meaning.

Similarly, the statement:

x.number = 100;

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:

x.putdata();

sends a message to the object x requesting it to display its contents.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *