Domanda

I want to define the object of a class within a structure and access function members of the class. Is it possible to achieve this?

With the following code I am getting a segmentation fault at ps_test->AttachToInput(2145);. I can't figure out the reason, everything looks correct to me:

class test
{
public:
    test();
    virtual ~test();
    int init_app(int argc, char* argv[]);   
    virtual void AttachToInput(int TypeNumber, int DeviceNo=0);
}

struct capture
{
    test h_app;
    gint port;
};

main()
{
    struct capture h_cap;
    test *ps_test = &h_cap.h_app;
    ps_test->AttachToInput(2145);
}
È stato utile?

Soluzione

First of all, the only difference between a class and a struct in C++ is that a class' members are private by default and a struct's members are public by default. Compiler-generated ctors and dtors are visible in both cases - unless otherwise stated by the programmer (e.g. they move the default ctor into a private section). Otherwise construction and destruction of instances of user-defined types marked class wouldn't be possible without explicit, public declaration - thus defying the very purpose of compiler-generated functions.

So basically, what you do in your example is merely composition of two user defined types which is perfectly legal. When you create an instance of capture, an instance of test is created as well.

What you can't do is publicly access AttachToInput() from outside of test and derived types of test. You need to declare the function public in order for this line to compile:

h_cap.h_app.AttachToInput(); // error: member function of `test` is protected

On another, unrelated note (but I came across it so I mention it), your class test holds a raw pointer to char. Holding raw pointers is ok, if the lifetime of the entity that's being pointed is guaranteed to exceed the lifetime of the object that holds the pointer. Otherwise, it's very likely the object itself is responsible for the destruction of said entity. You need to be sure about who owns what and who's responsible for allocation and deallocation of stuff.

EDIT: It should be noted, that Alan Stokes proposed the same in the comment section while I wrote this answer. :)

EDIT2: Slight oversight, implicit default access is also assumed for base classes depending on how the derived class is declared. See What are the differences between struct and class in C++?.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top