Accessing Private Class Members - C++ Class

C++ examples for Class:Member Field

Introduction

To provide access to the dimensions of a Pool object from outside the class, add three functions to the class definition:

class Pool
{
private:
  double length;
  double width;
  double height;

public:
  // Constructors
  Pool(double lv = 1.0, double wv = 1.0, double hv = 1.0);

  double volume();                                  // Function to calculate the volume of a pool

  // Functions to provide access to the values of data members
  double getLength() {return length;}
  double getWidth()  {return width;}
  double getHeight() {return height;}
};


Pool myPool {3.0, 4.0, 5.0};
std::cout << "myPool dimensions are" << myPool->getLength() << " by "
          << myPool->getWidth() << " by " << myPool->getHeight() << std::endl;

Related Tutorials