Home

Classes and Pointers to Pointers

 

Declaring a Pointer to Pointer

In Lesson 3, we saw how to declare a pointer to a pointer to a primitive type. In the same way, you can declare a pointer to a pointer to a class. Here is an example:

using namespace System;

public value struct CSquare
{
    double Side;
};

int main()
{
    CSquare **square;

    Console::WriteLine();
    return 0;
}

One way you can use such a variable is to initialize it with a reference to a pointer of the same type. This could be done as follows:

using namespace System;

public value struct CSquare
{
    double Side;
};

int main()
{
    CSquare *sqr = new CSquare;
    CSquare **square;

    square = &sqr;

    Console::WriteLine();
    return 0;
}

Remember that, for a double-pointer to a class, such as **square, the expression *square is a pointer to the class. This means that you can use the single asterisk to access the (public) members of the object. To do this, you can use the arrow -> operator. Because the -> operator has higher precedence than the asterisk, you must isolate *square by including it in parentheses. This would be done as follows:

using namespace System;

public value struct CSquare
{
    double Side;
};

int main()
{
    CSquare *sqr = new CSquare;
    CSquare **square;

    square = &sqr;

    (*square)->Side = 24.48;

    Console::WriteLine("Square Characteristics");
    Console::Write("Side: ");
    Console::WriteLine((*square)->Side);

    delete sqr;

    Console::WriteLine();
    return 0;
}

You may remember that the name of a pointer variable preceded with the asterisk represents the value held by the variable. When applied to a class, for a single pointer, the name preceded with * is the value of the variable. For a double-pointer, the name preceded with two asterisks is the value held by the pointer to pointer. This allows you to access the members of the class using the period operator. The above program can be written as:

using namespace System;

public value struct CSquare
{
    double Side;
};

int main()
{
    CSquare *sqr = new CSquare;
    CSquare **square;

    square = &sqr;

    (**square).Side = 24.48;

    Console::WriteLine("Square Characteristics");
    Console::Write("Side: ");
    Console::WriteLine((*square)->Side);

    delete sqr;

    Console::WriteLine();
    return 0;
}

Just as demonstrated in Lesson 3, after initializing a pointer, if you change the value of the variable it points to, the pointer would be updated. If the variable was declared as a pointer to pointer and if you change either the pointer it points to, the pointer to pointer would be updated.

 

Previous Copyright © 2006 FunctionX, Inc. Next