Search code examples
c++oophandle

Passing a structure handle (converting C to C++ OOP)


Can you suggest a way how I could pass a "handle (*h)" inside an object? This is how my code looks like in C.

int open(const char *name, ini_file_t **);
int read(ini_file_t *h, const char *sn, const char *kn, int *);
int write(ini_file_t *h, char *sn, char *kn, int);
int ini_file_close(ini_file_t *h);

I am trying to do this in C++ eliminating the (*h).

XTextFile {
public:
int open(const char *name);
int read(const char *sn, const char *kn, int *);
int write(char *sn, char *kn, int);
int ini_file_close();
};

Can you share some tips how I could do this?

Or the question is am I on the right path on doing this in OOP?


Solution

  • This would be my interpretation:

    class XTextFile
    {
        public:
        XTextFile(const std::string& name);// constructor replaces open()
        ~XTextFile();// destructor replaces ini_file_close
        int read(const std::string& sn, const std::string& kn, int *);
        int write(char *sn, char *kn, int);// not sure what these params are but they should also probably be some form of std::string
    };
    

    C++ constructors are used to initialize an object, and the destructor cleans up its resources when it's free'd. You would use this object like this:

    void someFunction()
    {
        XTextFile txt("c:\\filename.txt");
        txt.read(....);
        // txt is automatically closed when it goes out of scope.
    }