Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making C++ Classes inherit from C Structs, Recommended?

Tags:

c++

class

struct

I was recently doing some Windows Api coding (still doing it). And I was trying to find the best way to wrap the WNDCLASSEX into a C++ class, when I had this crazy idea, the WNDCLASSEX is a struct right? (even though it is written in c) and in C++ structs are treated as classes, so why don't I declare my WinCLass as a derivative of WNDCLASSEX , so I tried:

 class WinClass : protected WNDCLASSEX

And it worked! Then I tried using it with SDL structs but those worked too. But some structs(especially SDL ones) either don't compile or cause unexplained runtime errors when I derive classes from them. So my question: Is this kind of C struct use recommended? Is it actually used by pros, or is it just a lame hack? Should I use for my wrapppers or apps, or will this just introduce unexplained bugs?

like image 298
ApprenticeHacker Avatar asked Jul 17 '11 05:07

ApprenticeHacker


People also ask

Can you inherit from a struct C?

Structs do not support inheritance, but they can implement interfaces.

Can you do inheritance with structs?

Structs cannot have inheritance, so have only one type. If you point two variables at the same struct, they have their own independent copy of the data. With objects, they both point at the same variable.

Can we define class with struct if so is it possible to inherit a struct from another?

Yes, struct can inherit from class in C++. In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.

Why struct is faster than class?

The major difference between structs and classes is that they live in different places in memory. Structs live on the Stack(that's why structs are fast) and Classes live on Heap in RAM.


1 Answers

As long as you don't start adding virtual members, it should be fine. If you do add virtual members, the virtual table pointer could screw with your memory layout of the struct.

This includes virtual destructors!

like image 54
Blindy Avatar answered Oct 19 '22 23:10

Blindy