I have a structure in my program
struct secret_structure{
string a;
string b;
void *c;
};
I have a list of such structures
std::map<string name, secret_structure> my_map
I have to write a function that returns the structure by mapping it with the name.
get_from_map(string name, secret_structure * struct) //Kind of function
I have following options:
Pass a pointer of a secret_structure in the get_from_map function. The get_from_map populates the structure. I don't want to do this because the structure will be exposed.
I can have different functions for returning different values from the structure. Here the structure will not be exposed but does not look clean.
Can you help me with any other option such that the structure itself is not exposed.
Instead of passing a structure you could pass an handle that contains a pointer to the real object:
// public_interface.h
struct MySecretStruct; // I don't want to publish what's inside
struct WhatYouCanSee
{
MySecretStruct *msp; // The "P"ointer to "IMPLE"mentation
WhatYouCanSee(int a, double b);
~WhatYouCanSee();
WhatYouCanSee& operator=(const WhatYouCanSee&);
WhatYouCanSee(const WhatYouCanSee&);
void method1();
void method2(int x);
};
The methods will be just wrappers to calls to methods of the real object.
What you want is the pimpl idiom.
Pimple Idiom
Basically you declare a class that has an interface to the secret structure and holds a pointer to an instance of the secret structure. You can forward declare the struct without specifying implementation details. Then in the CPP file you access the secret structure. This can be provided in a header/binary format if you are providing it to 3rd parties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With