boom
boom

Reputation: 6166

including class as member in struct

I have to add a class object as member within a c struct.

Is there any prohibition doing this.

Regards, iSight

Upvotes: 8

Views: 13673

Answers (4)

Stephane Rolland
Stephane Rolland

Reputation: 39906

You CAN have a C++ class member in C, but it needs to be seen as a void* in the C point of view, so as the C can handle it fine.

This technique is called Opaque Pointer.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254451

I'll assume you're talking about C++, since there is no concept of a "class" in C - although you certainly can have a struct as a member of another struct.

Apart from one unimportant detail, class and struct are identical, and both are often referred to as "class types". Anything you can do with a class (such as having a member of class type), you can also do with a struct.

If you're interested, the only difference is the default accessibility of members and base classes; public for struct, and private for class.

Upvotes: 4

Axel
Axel

Reputation: 14159

As long as the struct is just used in C++ code, there's no problem. However, if the struct is passed to C code, bad things might happen (destructor not called when struct is freed/deleted).

If you don't see anything like extern "C" in the declaring file, you are probably safe.

Upvotes: 0

Kungi
Kungi

Reputation: 1536

No there is not. Check out this example:

#include<iostream>

class Foo {
    public:
        Foo() {
            this->i = 1;
        }
        int i;
};

struct Bar {
    Foo foo;
};

int main() {
    struct Bar bar;
    std::cout << bar.foo.i << std::endl;

    return 0;
}

Upvotes: 0

Related Questions