9.4 Class Scope and Accessing Class Members

A class’s data members and member functions belong to that class’s scope. Nonmember functions are defined at global namespace scope, by default. (We discuss namespaces in more detail in Section 23.4.)

Within a class’s scope, class members are immediately accessible by all of that class’s member functions and can be referenced by name. Outside a class’s scope, public class members are referenced through

  • an object name,

  • a reference to an object, or

  • a pointer to an object

We refer to these as handles on an object. The handle’s type enables the compiler to determine the interface (e.g., the member functions) accessible to the client via that handle. [We’ll see in Section 9.14 that an implicit handle (called the this pointer) is inserted by the compiler on every reference to a data member or member function from within an object.]

Dot (.) and Arrow (->) Member-Selection Operators

As you know, you can use an object’s name—or a reference to an object—followed by the dot member-selection operator (.) to access an object’s members. To reference an object’s members via a pointer to an object, follow the pointer name by the arrow member-selection operator (->) and the member name, as in pointerName->memberName.

Accessing public Class Members Through Objects, References and Pointers

Consider an Account class that has a public setBalance member function. Given the following declarations:


Account account; // an Account object

// accountRef refers to an Account object
Account& accountRef{account};

// accountPtr points to an Account object
Account* accountPtr{&account};

You can invoke member function setBalance using the dot (.) and arrow (->) member selection operators as follows:


// call setBalance via the Account object
account.setBalance(123.45);

// call setBalance via a reference to the Account object
accountRef.setBalance(123.45);

// call setBalance via a pointer to the Account object
accountPtr->setBalance(123.45);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset