Improving C++ Encapsulation with the Pimpl Idiom: Listing 1

Type members are explicit instances, not references.

#include <string>
#include <iostream>

using namespace std;

class A {
  int m, n; // private by default in a class
protected:
  char c;
public:
  string s{"Hello, world!"};
};

struct B {
  int i; // public by default in a struct
private:
  A a;
};

int main(int argc, char* argv[]) {
  cout << "Size of type A is " << sizeof(A) << endl;
  cout << "Size of type B is " << sizeof(B) << endl;
  // prints:
  // Size of type A is 24
  // Size of type B is 32
}

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at [email protected].

comments powered by Disqus

Featured

Subscribe on YouTube