Using a class with private data members : private « Class « C++ Tutorial






#include <iostream>

#include <iostream>
using std::cout;
using std::endl;

class Box {
  public:
    Box(double lvalue, double wvalue, double hvalue) :length(lvalue), width(wvalue), height(hvalue) {
      cout << "Box constructor called" << endl;
    }
    Box() {
      cout << "Default constructor called" << endl;
      length = width = height = 1.0;          // Default dimensions
    }
    double volume() {
      return length * width * height;
    }
  private:
    double length;
    double width;
    double height;
};

int main() {
  cout << endl;

  Box firstBox(2.2, 1.1, 0.5);
  Box secondBox;

  Box* pthirdBox = new Box(15.0, 20.0, 8.0);

  cout << firstBox.volume()<< endl;

  cout << secondBox.volume()<< endl;

  cout << pthirdBox->volume()<< endl;

  delete pthirdBox;
  return 0;
}
Box constructor called
Default constructor called
Box constructor called
1.21
1
2400








9.9.private
9.9.1.private fields
9.9.2.private by default
9.9.3.Non-friend/non-member functions cannot access private data of a class
9.9.4.Using a class with private data members