Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use struct as base for derived class in C++

Tags:

c++

c

casting

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

like image 921
jean Avatar asked Jan 19 '26 06:01

jean


1 Answers

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.

like image 51
sbi Avatar answered Jan 20 '26 20:01

sbi