C++ Class or Struct Compatiblity with C Struct

C++ Class or Struct compatiblity with C struct

Yes.

  • Use the same types in the same order in both languages
  • Make sure the class doesn't have anything virtual in it (so you don't get a vtable pointer stuck on the front)
  • Depending on the compilers used you may need to adjust the structure packing (usually with pragmas) to ensure compatibility.

(edit)

  • Also, you must take care to check the sizeof() the types with your compilers. For example, I've encountered a compiler that stored shorts as 32 bit values (when most will use 16). A more common case is that an int will usually be 32 bits on a 32-bit architecture and 64 bits on a 64-bit architecture.

C/C++ Struct vs Class

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

When should you use a class vs a struct in C++?

The differences between a class and a struct in C++ are:

  • struct members and base classes/structs are public by default.
  • class members and base classes/structs are private by default.

Both classes and structs can have a mixture of public, protected and private members, can use inheritance, and can have member functions.

I would recommend you:

  • use struct for plain-old-data structures without any class-like features;
  • use class when you make use of features such as private or protected members, non-default constructors and operators, etc.

Why do both struct and class exist in C++?

Why do both struct and class exist in C++?

A reason for existence of struct is for compatibility with C.

Why then, did "C with Classes" introduce the new keyword class when you could use struct for the same thing, you may ask. See this SO answer for plausible speculation. In short, it's probably because there was desire for emphasis on OOP in which class is a widely used term. Only Stroustrup may know for certain.

Confusingly, the keywords themselves do not necessarily correspond to the language used in the standard

What needs to be understood, is that the concept of a class is not one and the same with the keyword class.

There are three keywords for declaring classes. These keywords known as class-keys are class, struct and union. The non-union classes that are declared with either class or struct are exactly the same thing, except for . Union classes are different from non-union classes.

However, struct explicitly cannot be used in a template declaration to introduce type template parameters

C++ re-uses keywords for different purposes in different contexts. class keyword in a class declaration context, is not entirely the same as class keyword in a template argument definition. One keyword being equivalent to another in one context does not make it equivalent in all contexts. The reason for reusing keywords in different but similar contexts (static is another example), is to avoid introducing new keywords, which introduces more holes with compatibility with C (or earlier C++ standard) that does not have the new keywords.

The reason why class keyword was reused in the context of template type arguments was probably because classes are types, and therefore typically used as type parameters. There is also a typename keyword, which was added later and is (almost) interchangeable with class in template type argument declaration, but also used elsewhere (dependent type names) where class is not used. See this answer for a link and a summary about why a separate keyword was added to that context.

Why struct is not used in the context as an equivalent, you may ask. Well, that's another question to Stroustrup or the committee. It's an opposite choice than what committee did when enum class/enum struct was introduced.

I'm unable to see any significant difference between struct and class

Good. There isn't any except for

This seems rather redundant and confusing while introducing a glaring inconsistency.

I see no inconsistency in the quote from the standard. I see redundancy and I suspect that the redundancy exists to make it extra clear that a class declared with the keyword struct is still a class.

  1. Are there any technical differences that I have missed that significantly distinguish struct and class?

I've already answered, but to be clear, there is no difference between classes declared with struct and class keywords, beyond .

the difference with the default access specifier (as you already know, and also described here), which is their only difference.

Why do we need a `class` in C++, when a `struct` can be used to achieve the same?

You don't need classes, the language just gives you another option to choose from. Technically, you're right, you can achieve anything a class can do with a struct.

Besides the default access level, there's also the meaning most programmers associate with the two - struct generally means a light-weight, typically POD, data-type with little to no functionality. A class is usually associated with something bigger.

Why does C++ have both classes and structs?

First, it's backward compatibility with C.
Second (and more importantly), it helps describe your intent. The standard convention is that PODs should be denoted with struct and collections of data and behavior should be denoted with class.

What are the differences between struct and class in C++?

You forget the tricky 2nd difference between classes and structs.

Quoth the standard (§11.2.2 in C++98 through C++11):

In absence of an access-specifier
for a base class, public is assumed
when the derived class is declared
struct and private is assumed when the class is declared class.

And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):

Member of a class defined with the
keyword class are private by
default. Members of a class defined
with the keywords struct or union
are public by default.

Additional difference: the keyword class can be used to declare template parameters, while the struct keyword cannot be so used.

C++: Are Structs really the same as Classes?

There is no difference between structs and classes besides the default for protection (note that default protection type for base classes is different also). Books and my own 20+ years experience tells this.

Regarding default empty ctor/dector. Standard is not asking for this. Nevertheless some compiler may generate this empty pair of ctor/dector. Every reasonable optimizer would immediately throw them away. If at some place a function that is doing nothing is called, how can you detect this? How this can affect anything besides consuming CPU cycles?

MSVC is not generating useless functions. It is reasonable to think that every good compiler will do the same.

Regarding the examples

struct SomeStruct
{
int field1;
char field2;
double field3;
bool field4;
};

void SomeFunction()
{
int field1;
char field2;
double field3;
bool field4;
...
}

The padding rules, order in memory, etc may be and most likely will be completely different. Optimizer may easily throw away unused local variable. It is much less likely (if possible at all) that optimizer will remove a data field from the struct. For this to happen the struct should be in defined in cpp file, certain flags should be set, etc.

I am not sure you will find any docs about padding of local vars on the stack. AFAIK, this is 100% up to compiler for making this layout. On the contrary, layout of the structs/classes are described, there are #pargma and command line keys that control this, etc.

Using C++ struct in C

You can access the members of a struct written in C++ from a C-program given you ensure that the C++ additions to the struct syntax are removed:

// header
struct S {
int a, b;

#ifdef __cplusplus
void foo();
#endif
};

// c-file:
#include "header.h"

void something(struct S* s)
{
printf("%d, %d", s->a, s->b);
}

The memory layout of structs and classes in C++ is compatible with C for the C-parts of the language. As soon as you add a vtable (by adding virtual functions) to your struct it will no longer be compatible and you must use some other technique.



Related Topics



Leave a reply



Submit