tags:

views:

282

answers:

3

Is it possible to have a class inheriting from a struct?

More specifically, how can I wrap a C struct with a class, so that I can pass class pointers to methods that requires struct ptr and cast back when I receive the pointer in e.g. callbacks?

(Or even more specifically, the address of the class should be same same address as the struct...)

+4  A: 

You just derive from the C struct. In C++, the only difference between a struct and a class is that the latter's default member accessibility is private, while the former's is public.

If only single inheritance is involved, the class's address should be the same as the struct's which acts as a base class. If the inheritance only serves the implementation (that is, there is no Is-A relationship between the two), consider using private inheritance.

sbi
+2  A: 

yes, in C++ a class is a struct with default private members, and a struct is a class with default public members. Therefore a Class can be derived from a struct.

The choice on the method to wrap structure A in class B is the usual in OO design: B is a A: use inheritance B contains a A, use Composition: make A a memberof B.

sergiom
+2  A: 

By definition, a struct is a class in which members are by default public; that is,

struct person
{
};

is equals to:

class person
{
  public: //...
};

Another difference, that by default (without explicit access modifier) class inheritance means private inheritance, and struct inheritance means public inheritance.

struct person {...};
struct employee : person {...}; 

Means public inheritance, i.e. there is IS A relationship and implicit conversion between employee and person;

class person {...};
class employee : person {...};

Means private inheritance (i.e. employee IMPLEMENTED IN TERMS OF relationship and no implicit conversion between employee and person).

In your case classes and structs are interchangeable;

Sergey Teplyakov