A name can be hidden by declaring that name in an enclosed block. In Figure 2.1, i is redeclared within the inner block, thereby hiding the variable associated with i in the outer block scope.
The output from the program shown in Figure 2.1 is:
i = 0
i = 7
j = 9
i = 0
Note:
The argument szWhat is considered to be in the scope of the function. Therefore, it is treated as if it had been declared in the outermost block of the function.
Names with file scope can be hidden by explicitly declaring the same name in block scope. However, these names can be accessed using the scope-resolution operator (::). For example:
#include <iostream.h>
int i = 7; // i has file scope--declared
// outside all blocks
int main( int argc, char *argv[] )
{
int i = 5; // i has block scope--hides
// the i with file scope
cout << "Block-scoped i has the value: " << i << "\n";
cout << "File-scoped i has the value: " << ::i << "\n";
return 0;
}
The result of the preceding code is:
Block-scoped i has the value: 5
File-scoped i has the value: 7
Class names can be hidden by declaring a function, object or variable, or enumerator in the same scope. However, the class name can still be accessed when prefixed by the keyword class.
// Declare class Account at file scope.
class Account
{
public:
Account( double InitialBalance )
{ balance = InitialBalance; }
double GetBalance()
{ return balance; }
double Deposit( double HowMuch )
{ return balance += HowMuch; }
double Withdraw( double HowMuch )
{ return balance -= HowMuch; }
private:
double balance;
};
double Account = 15.37; // Hides class name Account
int main( int argc, char *argv[] )
{
class Account Checking( Account );
cout << "Opening account with balance of: "
<< Checking.GetBalance() << "\n";
cout << "Depositing $10.57, for a remaining balance of: "
<< Checking.Deposit( 10.57 ) << "\n";
cout << "Withdrawing $27.16, for a remaining balance of: "
<< Checking.Withdraw( 27.16 ) << "\n";
return 0;
}
Note that any place the class name (Account) is called for, the keyword class must be used to differentiate it from the function-scoped variable Account. This rule does not apply when the class name occurs on the left side of the scope-resolution operator (::). Names on the left side of the scope-resolution operator are always considered class names. The following example demonstrates how to declare a pointer to an object of type Account using the class keyword:
class Account *Checking = new class Account( Account );
Note that the Account in the initializer (in parentheses) in the preceding statement has function scope; it is of type double.
(For more information about pointers, see “Derived Types”. For information about declaration and initialization of class objects, see Chapter 8, “Classes.” For information about using the new and delete free-store operators, see Chapter 11, “Special Member Functions.”)