Created
August 24, 2019 03:19
-
-
Save haxpor/0be8a04e9fef03ab28bc2b2f7fa35e39 to your computer and use it in GitHub Desktop.
Demonstrate hiding structure layout to public but still allow access.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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