Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created August 24, 2019 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/0be8a04e9fef03ab28bc2b2f7fa35e39 to your computer and use it in GitHub Desktop.
Save haxpor/0be8a04e9fef03ab28bc2b2f7fa35e39 to your computer and use it in GitHub Desktop.
Demonstrate hiding structure layout to public but still allow access.
#include <iostream>
#include <string>
struct PublicData
{
int a;
float b;
// private data
// this is a technique to hide the struct information thus users won't be able to know its layout
// although users can still access each member of struct
struct {
int c;
double d;
std::string e;
} d;
};
static void PrintInfo(const PublicData& pb)
{
std::cout << pb.a << "\n" << pb.b << "\n" << pb.d.c << "\n" << pb.d.d << "\n" << pb.d.e << std::endl;
}
int main()
{
// This initialization is also possible
PublicData pb {
1,
2.5f,
1,
2,
"Test"
};
PrintInfo(pb);
// Maual initialization for each of member variable
PublicData pb_man;
pb_man.a = 2;
pb_man.b = 3;
pb_man.d.c = 1;
pb_man.d.d = 2.2f;
pb_man.d.e = "Test2";
PrintInfo(pb_man);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment