Object sizes : sizeof « Operators statements « C++ Tutorial






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

class Box {
  public:
    Box() :length(1.0), width(1.0), height(1.0), pMaterial("new") {}
    
    int totalSize() {
      return sizeof(length) + sizeof(width) + sizeof(height) + sizeof(pMaterial
);
    }
  private:
    char* pMaterial;
    double length;
    double width;
    double height;
};

int main() {
  Box box;
  Box boxes[10];
  cout << endl            << "The data members of a Box object occupy "
       << box.totalSize() << " bytes.";

  cout << endl           << "A single Box object occupies "
       << sizeof (Box) << " bytes.";

  cout << endl           << "An array of 10 Box objects occupies "
       << sizeof(boxes)  << " bytes."
       << endl;
  return 0;
}
The data members of a Box object occupy 28 bytes.
A single Box object occupies 32 bytes.
An array of 10 Box objects occupies 320 bytes.








3.6.sizeof
3.6.1.Demonstrate sizeof.
3.6.2.sizeof a union
3.6.3.sizeof a class
3.6.4.Object sizes
3.6.5.Using the sizeof operator for base class and derived class
3.6.6.Use sizeof operator on an array name: returns the number of bytes in the array