What Are the Differences Between Struct and Class in C++

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.

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.

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

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

  • struct members and base classes/structs are public by default.
  • class members and base classes/struts 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.

What's the difference between struct and class in .NET?

In .NET, there are two categories of types, reference types and value types.

Structs are value types and classes are reference types.

The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.

A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.

This has one benefit, to begin with:

  • value types always contains a value
  • reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:

  • copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
  • copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

When you declare variables or fields, here's how the two types differ:

  • variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note Eric Lipperts article series: The Stack Is An Implementation Detail.)
  • class/struct-field: value type lives completely inside the type, reference type lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.

Difference between a struct and a class [duplicate]

In C++, the only difference between a struct and a class is that struct members are public by default, and class members are private by default.

However, as a matter of style, it's best to use the struct keyword for something that could reasonably be a struct in C (more or less POD types), and the class keyword if it uses C++-specific features such as inheritance and member functions.

C does not have classes.

C structs cannot use C++-specific features.

EDIT:

The C++ FAQ Lite, question 7.9, has this to say:

The members and base classes of a struct are public by default,
while in class, they default to private. Note: you should make
your base classes explicitly public, private, or protected,
rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most
developers make a strong distinction between a class and a struct.
A struct simply feels like an open pile of bits with very little
in the way of encapsulation or functionality. A class feels like a
living and responsible member of society with intelligent services, a
strong encapsulation barrier, and a well defined interface. Since
that's the connotation most people already have, you should probably
use the struct keyword if you have a class that has very few methods
and has public data (such things do exist in well designed
systems!), but otherwise you should probably use the class keyword.

And quoting Stroustrup's "The C++ Programming Language", 4th edition, section 16.2.4:

These two definitions of S are interchangeable, though it is
usually wise to stick to one style. Which style you use depends on
circumstances and taste. I tend to use struct for classes that I
think of as "just simple data structures." If I think of a class as "a
proper type with an invariant," I use class. Constructors and
access functions can be quite useful even for *struct*s, but as a
shorthand rather than guarantors of invariants.

C++: Are Structs really the same as Classes? [duplicate]

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.

is there a difference between a struct in c++ and a struct in c#?

In C# you use structs to define value types (as opposed to reference types declared by classes).

In C++, a struct is the same thing as a class with a default accessibility level of public.

So the question should be: are structs in C# different from classes in C++ and, yes, they are: You cannot derive from C# structs, you cannot have virtual functions, you cannot define default constructors, you don't have destructors etc.

Difference between struct and class in older c++ versions

Pretty much always.

It has been this way since long before standardisation, practically since the first draft revisions in the 80s.

Frustratingly, Stroustrup's "A History of C++" does not discuss this, but types known as "classes", defined using the struct keyword, could be found as early as "The C++ Programming Language - Reference Manual", which was the first specification following the "C with Classes" research phase and thus effectively the first pre-standard C++ revision:

classes containing a sequence of objects of various types, a set of functions for manipulating these objects, and a set of restrictions on the access to these objects and functions;

structures which are classes without access restrictions

This was known as "Release E", and came in November 1984.

By Release 2.0 in 1989, this had been relaxed to the rule we have today:

structures which are classes without default access restrictions

For a temporal reference, the first version of what we now call "C++" was standardised in 1998.

What is the difference between C structures and Java classes?

If you leave method overriding out of the picture, then you can think of Java classes and methods as a pair of a C-style struct and a set of functions that operate on those structs. For example, if you have a class like this:

 public class MyJavaClass {
private int x;
public int getX() {
return x;
}
public int setX(int value) {
x = value;
}
}

This would be similar to writing C code to this effect:

struct MyJavaClass {
int x;
};

int MyJavaClass_getX(struct MyJavaClass* this) {
return this->x;
}
void MyJavaClass_setX(struct MyJavaClass* this, int value) {
this->x = value;
}

The main idea is that a method is similar to a function that takes the receiver object as an implicit "this" parameter. In C, you have to explicitly pass the receiver as a parameter to the function, while in Java this is done implicitly through the object.method() syntax.

If you start introducing method overriding, this becomes a bit more complicated because the method that you invoke on an object depends on the dynamic type of the object, not the static type. One way of simulating this is using something called a vtable or virtual function table, so named because of C++'s virtual keyword. The idea is that each object stores a pointer to a table of function pointers, one per function that can be overridden, and when a method is called on the object the appropriate function pointer is selected out of the table and called. So, more properly, the above Java object might look something like this:

struct MyJavaClass_Vtable {
void (*getX)(struct MyJavaClass* this);
void (*setX)(struct MyJavaClass* this, int value);
};

struct MyJavaClass {
struct MyJavaClass_Vtable* vtable;
int x;
};

int MyJavaClass_getX(struct MyJavaClass* this) {
return this->x;
}
void MyJavaClass_setX(struct MyJavaClass* this, int value) {
this->x = value;
}

/* A global instance of the vtable for MyJavaClass */
struct MyJavaClass_Vtable MyJavaClassVtableInstance = {
&MyJavaClass_getX,
&MyJavaClass_setX
};

Whenever you created an instance of MyJavaClass, you'd set up its vtable doing something like this:

struct MyJavaClass* mjc = malloc(sizeof *mjc);
mjc->vtable = &MyJavaClassVtableInstance;

Then, when invoking a function like this (in Java):

myJavaClass.getX();

In C it would look like

myJavaClass->vtable->getX(myJavaClass);

So in a sense a Java class is just a struct with some extra metainformation. Of course, to the programmer it looks totally different - there's encapsulation, polymorphism, a stricter type system, etc. - but at the level of native code a regular C struct and a Java class probably look very similar.

Hope this helps!



Related Topics



Leave a reply



Submit