Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct is unboxed while C++ struct is a boxed type?

Tags:

c++

c

struct

As many books mentioned, the difference with C++ struct and class is the access control descriptor. Thus I am wondering if the following statement is right:

struct in C is unboxed: members in the struct are plainly located next to where the struct is allocated. But struct in C++ is a boxed type like class: members/headers are located somewhere else, and where the struct is allocated contains a pointer to the members/headers.

Is this understanding right?

And is it possible to create a unboxed type in C++, that also contains instance methods?

like image 997
qinsoon Avatar asked Sep 12 '25 05:09

qinsoon


2 Answers

Looks like complete nonsense to me.

Members are not magically "located somewhere else", no pointers are involved, and headers have nothing to do with it whatsoever. The C++ compiler doesn't even know that headers exist!

like image 54
Lightness Races in Orbit Avatar answered Sep 14 '25 18:09

Lightness Races in Orbit


The missing keyword in this discussion is 'POD' (Plain Old Data structure). (Boxing is related to .NET and possibly Java - though I don't recall Java terminology using the word)

A POD basically means that it can be moved around in memory just by 'blitting bits' (memcpy, memmov). There are explicit requirements in the C++ standard specifications.

C structs are always POD (plain old data), whereas C++ classes can have 'extra magic' related to (virtual) inheritance.

Look at this:

What are POD types in C++?

like image 45
sehe Avatar answered Sep 14 '25 20:09

sehe