Difference between struct and class? [duplicate] - c++

This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 8 years ago.
Is the size of a struct and the size of the equivalent class guaranteed to be equal?

Essentially struct and class are identical in C++, with 2 differences:
Members of a struct are public by default, while in a class they're private. Access modifiers still apply when supplied by the programmer.
When deriving a struct from a class or struct, the default access modifier for the base is public. And when deriving a class, the default access is private.
In general, programmers assume that in a struct all members are public and freely modifiable, and in a class they will all be private and getters/setters will be present as appropriate. This is merely convention though and not enforced by the language.
Since they are treated identically by the compiler apart from the default access, sizes are guaranteed to be identical. The main reason that both keywords are historically supported by C++, even though slightly redundant, is backwards compatibility with C where only struct exists.

Assuming you're asking about CPP.
Members of a struct are public by default.
In a class, they default to private.
struct and class are otherwise functionally equivalent.
structs are typically used as open data containers.
The size of a class and structure will tend to be the same given that the ordering of its data members are in the same order and you did not change the default member alignment.

Related

Speed of data access in Structs vs Objects, C++ [duplicate]

This question already has answers here:
Performances of Structs vs Classes
(7 answers)
Closed 9 years ago.
I was wondering if there is a difference in the running time of accessing data from a Struct and accessing data from an Class in C++. In my current understanding, a Struct is a class but with no member functions. I have some code which runs much more slowly with objects than with structs, which seems to suggest that there is a difference, but this confuses me as my intuition tells me that there shouldnt be a large difference.
As per " What are the differences between struct and class in C++? ", quoting from C++ FAQ
struct and class are otherwise functionally equivalent
(aside from minor private/public/protected defaults).
So there's no difference.
It is all the same, whether it is a struct or a class (I assume that it what you mean by object, since any instance is technically an object, be that a primitive, a struct or a class), the compiler does the same offset calculation to access members. There isn't really that much of a difference between the two - they may look different in terms of syntax, but the C++ call someObject.someMethod() is equivalent to the C version SomeObject_someMethod(&someObject) which is what a member call really is under the table. But this only concerns member methods, the access speed to members of classes and structs is practically identical.
I don't know why you would have that problem of different running times.
Structs and Classes, I'm assuming thats what you mean by objects, are virtually the same other than structs defaulting to public and classes defaulting to private.
So to sum it up there should be no difference functionally or speed wise
EDIT: the reason you may be experiencing structs running faster is because people tend to use structs for POD's whereas classes have more functionality, however this is based on style not actual the functionality of structs and classes
At runtime execution there is no difference in speed of execution.
you can refer similar threads.
Performances of Structs vs Classes
Class vs Struct for data only?
in C++ there are 3 kind of objects that belong to the class type:
struct
class
unions
they are functionally equivalent to each other, so you should expand more and tell more about your implementation.

Structures vs objects C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
C++ - struct vs. class
How are structures different from objects and classes in C++? Is there any performance benefit to using objects or structures?
Structures and classes are identical; the language standard uses the term "class" to refer to both. The only difference between defining a class using the struct or the class keyword is the default accessibility of members and base classes; there is no difference in their runtime behaviour or performance.
An "object" is a run-time instance of a type. In C++, the term is used for instances of any type, including classes and fundamental types.
main thing is by default variables are private in a class and by default they are public in structures. also you can google this and find a million and one topics on this. for example http://blog.stevedoria.net/20050913/differences-between-cpp-classes-and-structs

Difference between a struct and a class [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
I've done my homework and had diverse answers on Google.
Some say structs do not have inheritance, some say structs do not have access specifiers, while others say they have both.
Could someone clarify then, the differences between a struct and a class in C and C++, and also the difference between a struct in C & C++.
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.
In C, classes do not exist. In C++, structs have a default access specifier of public, while classes default to private.
There are several differences between structs in C and C++; in C++ they can inherit from other classes or structs, they can contain member functions, and their names don't need to be referred to with an elaborated type specifier.

In C++, why struct is in fact class?

The other topic and responses there made me ask this question:
Why does C++ allow struct to behave just like class? At one hand, C++ made it compatible with C-struct by making it's members public by default (just like in C), while on the other hand, it made it look-like class by allowing it to be inherited from classes, and applying other object-oriented techniques (not so much like C-struct anymore). Why did it not make it just plain old C-struct with no OOP? Any special reason?
It allows existing structs to be fitted in with C++ code in a more natural way. For instance, you can add member functions to a struct and inherit from a struct, which wouldn't be possible if structs and classes inhabited different universes.
Stroustrup's original intent was to avoid a fracturing of the community between the traditional C-style "struct" camp, and the OO "class" crowd. He also cited the benefits of having just one concept instead of two.
From a language point of view, structures and unions are just types of class. It makes the language specification simpler if there are fewer concepts (with a small letter 'c') and it also makes specifying the language less error prone as it is less easy to miss something 'obvious' out if every common property had to spelled out for each of structures, unions and non-structure, non-union classes.
C++ classes have a lot of potential functionality over C structures but as C structures can be viewed as a degenerate C++ class, it is simplest to allow them to be exactly this. There is no benefit to having a special structure concept as well as a class concept.
From ISO/IEC 14882:2003, 9 [class] / 4:
A structure is a class defined with the class-key struct; its members and base classes are public by default. A union is a class defined with the class-key union; its members are public by default and it holds only one data member at a time.
"public" default for struct fields is required for compatibility with C
code which may access struct fields.
"public" default for struct inheritance is required so that the child class
could be used in place of base struct.
It could be possible to make struct into a different data type than classes
(ie disallow access type specifiers and methods in it), but that would be both
inconvenient for programming and add a lot of unnecessary work for compiler
developers.
In C there were only structs to begin with. Object orientation began when libraries were designed when pointers to those structures were passed to a set of library functions that were dependent on that structure. One good example is the Win32 API. It isn't a C++ interface, it's a C interface; but it's still object oriented.
Classes are almost the same as structures memory-wise. The member functions are not stored as part of the class member data. It's simply a structure with extra function pointers on the end. So a class' function table is dereferenced in the same way that Windows API uses object orientation, but it encapsulates it so you don't see it.
Inheritance, polymorphism; who cares? People were fine with C, and still doing fine with C.
Allowing something you declare as struct to really be a class allows type-safety when creating a C interface.
You can forwardly declare your struct for your C interface:
struct Foo;
You can declare methods on it
void doStuffThatModifiesFoo( struct Foo * foo, ... );
struct Bar getStuffFromFoo( const struct Foo * foo );
You can also write create and destroy methods for it.
Underneath you implement Foo not as a C struct but as a class but your C clients do not need to know that. This is better than passing it around as a void * then casting (not safe if someone passes you a void* to a completely different type and you cast it).
The "compatibility with C" issue is only meant in one direction: Old, valid C-code should also compile as C++ code. The other way round is impossible as soon as any language feature that only C++ has is being used.
That means in C++, you always write classes, you can omit using the keyword struct at all ; though some, including me, think they come in handy to show that a class just a simple collection of named values, with no real encapsulation or possibly complex behaviour.

Unions as Base Class

The standard defines that Unions cannot be used as Base class, but is there any specific reasoning for this? As far as I understand Unions can have constructors, destructors, also member variables, and methods to operate on those varibales. In short a Union can encapsulate a datatype and state which might be accessed through member functions. Thus it in most common terms qualifies for being a class and if it can act as a class then why is it restricted from acting as a base class?
Edit: Though the answers try to explain the reasoning I still do not understand how Union as a Derived class is worst than when Union as just a class. So in hope of getting more concrete answer and reasoning I will push this one for a bounty. No offence to the already posted answers, Thanks for those!
Tony Park gave an answer which is pretty close to the truth. The C++ committee basically didn't think it was worth the effort to make unions a strong part of C++, similarly to the treatment of arrays as legacy stuff we had to inherit from C but didn't really want.
Unions have problems: if we allow non-POD types in unions, how do they get constructed? It can certainly be done, but not necessarily safely, and any consideration would require committee resources. And the final result would be less than satisfactory, because what is really required in a sane language is discriminated unions, and bare C unions could never be elevated to discriminated unions in way compatible with C (that I can imagine, anyhow).
To elaborate on the technical issues: since you can wrap a POD-component only union in a struct without losing anything, there's no advantage allowing unions as bases. With POD-only union components, there's no problem with explicit constructors simply assigning one of the components, nor with using a bitblit (memcpy) for compiler generated copy constructor (or assignment).
Such unions, however, aren't useful enough to bother with except to retain them so existing C code can be considered valid C++. These POD-only unions are broken in C++ because they fail to retain a vital invariant they possess in C: any data type can be used as a component type.
To make unions useful, we must allow constructable types as members. This is significant because it is not acceptable to merely assign a component in a constructor body, either of the union itself, or any enclosing struct: you cannot, for example, assign a string to an uninitialised string component.
It follows one must invent some rules for initialising union component with mem-initialisers, for example:
union X { string a; string b; X(string q) : a(q) {} };
But now the question is: what is the rule? Normally the rule is you must initialise every member and base of a class, if you do not do so explicitly, the default constructor is used for the remainder, and if one type which is not explicitly initialised does not have a default constructor, it's an error [Exception: copy constructors, the default is the member copy constructor].
Clearly this rule can't work for unions: the rule has to be instead: if the union has at least one non-POD member, you must explicitly initialise exactly one member in a constructor. In this case, no default constructor, copy constructor, assignment operator, or destructor will be generated and if any of these members are actually used, they must be explicitly supplied.
So now the question becomes: how would you write, say, a copy constructor? It is, of course quite possible to do and get right if you design your union the way, say, X-Windows event unions are designed: with the discriminant tag in each component, but you will have to use placement operator new to do it, and you will have to break the rule I wrote above which appeared at first glance to be correct!
What about default constructor? If you don't have one of those, you can't declare an uninitialised variable.
There are other cases where you can determine the component externally and use placement new to manage a union externally, but that isn't a copy constructor. The fact is, if you have N components you'd need N constructors, and C++ has a broken idea that constructors use the class name, which leaves you rather short of names and forces you to use phantom types to allow overloading to choose the right constructor .. and you can't do that for the copy constructor since its signature is fixed.
Ok, so are there alternatives? Probably, yes, but they're not so easy to dream up, and harder to convince over 100 people that it's worthwhile to think about in a three day meeting crammed with other issues.
It is a pity the committee did not implement the rule above: unions are mandatory for aligning arbitrary data and external management of the components is not really that hard to do manually, and trivial and completely safe when the code is generated by a suitable algorithm, in other words, the rule is mandatory if you want to use C++ as a compiler target language and still generate readable, portable code. Such unions with constructable members have many uses but the most important one is to represent the stack frame of a function containing nested blocks: each block has local data in a struct, and each struct is a union component, there is no need for any constructors or such, the compiler will just use placement new. The union provides alignment and size, and cast free component access.
[And there is no other conforming way to get the right alignment!]
Therefore the answer to your question is: you're asking the wrong question. There's no advantage to POD-only unions being bases, and they certainly can't be derived classes because then they wouldn't be PODs. To make them useful, some time is required to understand why one should follow the principle used everywhere else in C++: missing bits aren't an error unless you try to use them.
Union is a type that can be used as any one of its members depending on which member has been set - only that member can be later read.
When you derive from a type the derived type inherits the base type - the derived type can be used wherever the base type could be. If you could derive from a union the derived class could be used (not implicitly, but explicitly through naming the member) wherever any of the union members could be used, but among those members only one member could be legally accessed. The problem is the data on which member has been set is not stored in the union.
To avoid this subtle yet dangerous contradiction that in fact subverts a type system deriving from a union is not allowed.
Bjarne Stroustrup said 'there seems little reason for it' in The Annotated C++ Reference Manual.
The title asks why unions can't be a base class, but the question appears to be about unions as a derived class. So, which is it?
There's no technical reason why unions can't be a base class; it's just not allowed. A reasonable interpretation would be to think of the union as a struct whose members happen to potentially overlap in memory, and consider the derived class as a class that inherits from this (rather odd) struct. If you need that functionality, you can usually persuade most compilers to accept an anonymous union as a member of a struct. Here's an example, that's suitable for use as a base class. (And there's an anonymous struct in the union for good measure.)
struct V3 {
union {
struct {
float x,y,z;
};
float f[3];
};
};
The rationale for unions as a derived class is probably simpler: the result wouldn't be a union. Unions would have to be the union of all their members, and all of their bases. That's fair enough, and might open up some interesting template possibilities, but you'd have a number of limitations (all bases and members would have to be POD -- and would you be able to inherit twice, because a derived type is inherently non-POD?), this type of inheritance would be different from the other type the language sports (OK, not that this has stopped C++ before) and it's sort of redundant anyway -- the existing union functionality would do just as well.
Stroustrup says this in the D&E book:
As with void *, programmers should know that unions ... are inherently dangerous, should be avoided wherever possible, and should be handled with special care when actually needed.
(The elision doesn't change the meaning.)
So I imagine the decision is arbitrary, and he just saw no reason to change the union functionality (it works fine as-is with the C subset of C++), and so didn't design any integration with the new C++ features. And when the wind changed, it got stuck that way.
I think you got the answer yourself in your comments on EJP's answer.
I think unions are only included in C++ at all in order to be backwards compatible with C. I guess unions seemed like a good idea in 1970, on systems with tiny memory spaces. By the time C++ came along I imagine unions were already looking less useful.
Given that unions are pretty dangerous anyway, and not terribly useful, the vast new opportunities for creating bugs that inheriting from unions would create probably just didn't seem like a good idea :-)
Here's my guess for C++ 03.
As per $9.5/1, In C++ 03, Unions can not have virtual functions. The whole point of a meaningful derivation is to be able to override behaviors in the derived class. If a union cannot have virtual functions, that means that there is no point in deriving from a union.
Hence the rule.
You can inherit the data layout of a union using the anonymous union feature from C++11.
#include <cstddef>
template <size_t N,typename T>
struct VecData {
union {
struct {
float x;
float y;
float z;
};
float a[N];
};
};
template <size_t N, typename T>
class Vec : public VecData<N,T> {
//methods..
};
In general its almost always better not work with unions directly but enclose them within a struct or class. Then you can base your inheritance off the struct outer layer and use unions within if you need to.