Easy Tutorial
❮ Cpp Interfaces Cpp Sizeof Operator ❯

C++ Pointer to Class

C++ Classes & Objects

A pointer to a C++ class is similar to a pointer to a structure. To access members of a class using a pointer to the class, you need to use the member access operator ->, just like accessing a pointer to a structure. As with all pointers, you must initialize the pointer before using it.

The following example helps to better understand the concept of a pointer to a class:

#include <iostream>

using namespace std;

class Box
{
   public:
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout << "Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   Box *ptrBox;                // Declare pointer to a class.

   // Save the address of the first object
   ptrBox = &Box1;

   // Now try to access members using the member access operator
   cout << "Volume of Box1: " << ptrBox->Volume() << endl;

   // Save the address of the second object
   ptrBox = &Box2;

   // Now try to access members using the member access operator
   cout << "Volume of Box2: " << ptrBox->Volume() << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102

C++ Classes & Objects

❮ Cpp Interfaces Cpp Sizeof Operator ❯