Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - struct vs. class [duplicate]

Tags:

c++

People also ask

Is a struct in C the same as a 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.

Why struct is faster than class?

So based on the above theory we can say that Struct is faster than Class because: To store class, Apple first finds memory in Heap, then maintain the extra field for RETAIN count. Also, store reference of Heap into Stack. So when it comes to access part, it has to process stack and heap.

Does C Copy structs?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.

Is struct faster than class C++?

To answer your question, struct is slightly faster.


The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.


You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.

A quick Google search suggests that POD stands for "Plain Old Data".


POD classes are Plain-Old data classes that have only data members and nothing else. There are a few questions on stackoverflow about the same. Find one here.

Also, you can have functions as members of structs in C++ but not in C. You need to have pointers to functions as members in structs in C.


Ok, POD means plain old data. That usually refers to structs without any methods because these types are then used to structure multiple data that belong together.

As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.


1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD