Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a structure without exposing it

Tags:

c++

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:

  1. 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.

  2. 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.

like image 213
ajay bidari Avatar asked Dec 03 '22 22:12

ajay bidari


2 Answers

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.

like image 92
6502 Avatar answered Dec 14 '22 11:12

6502


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.

like image 31
Dominique McDonnell Avatar answered Dec 14 '22 10:12

Dominique McDonnell