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

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.

Related

Which one is best approach class or structs? In c++ [duplicate]

This question already has answers here:
When should you use a class vs a struct in C++? [duplicate]
(27 answers)
Closed 4 years ago.
Suppose you have to develop an application for XYZ bank with the following features.
1)The application must be secure
2)For transactions, proper interfaces will be provided to the customers.
3)The application must be reusable.
4)The application must be efficient in terms of speed and memory usage.
You can use either structs or class in order to achieve the above mentioned features. So which programming construct (class or struct) will you select for application development.
Please help me out here. Thanks
struct and class are nearly equivalent in C++ (you can have member functions, constructors & destructors, data members in both). More precisely,
struct Sometype {
/// some code here
};
is equivalent to
class Sometype {
public:
/// some code here
};
So the runtime efficiency is the same (since public: is an annotation for the compiler which is lost, as most type information, at runtime; be aware of type erasure).
You really should take days to read some good book about C++ programming, then look into some C++ reference site, then read (or at least refer to) some C++ standard like n3337 (for C++11; for later standards, find them by yourself).
Learn about the rule of five and about standard containers and smart pointers.

C++ Structs - Pointless? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
I'm just trying to figure out if using 'C structs' in C++ are essentially useless or not. Do you gain anything by using them (opposed to simply creating another class)?
In C the point of structs is obvious, simply contiguous allocations of grouped data and a nice way to access said data, in C++ I feel the role becomes a little more vague.
Seeing as that you can have functions which are members of structs, instance variables, and visibility labels, the only real difference that I see between structs and classes in C++ is that struct members default to public while class members default to private. The way I see them, they can actually both be implemented with the same exact underlying system.
So am I missing something here as to the purpose of structs in C++? Or have they kind of lost their purpose, as I feel they have in C++?
In my opinion, Structures doesn't give you anything that can't be implemented by a class.
But, Structures are kept in C++ in order to have backward compatibility with c
Classes and structures in C++ are almost the same, the only things that separates them is that the default visibility of a class is private while in a struct it's public.
The reason to keep having structures in C++ was probably to keep the language compatible with C, so it would be easier to port C code to C++, or for programmers to make that transition.
As for the usage of structures contra classes, I personally use them just like would in C, to group related variables together in a single "object".
Undoubtedly the reason they are there is for compatibility with C. But you are right, although there are small differences between class and struct in C++ there is nothing you can do with structs that you cannot do with classes (and vice versa).
Personally I use structs only when the same declaration would be legal in C, to emphasize the C-like nature of whatever it is I'm doing.
They are implemented "with the same exact underlying system". In fact, you can actually declare a type using class keyword and then define it using struct keyword. Basically, they are exactly the same aside from the conceptual difference you already mentioned: default access rights.
I don't see though why would one call them "useless". The usage of the keyword became a matter of personal preference and/or coding standard. Like "use struct fro POD types", or "use struct for types with no incapsulation/access control".
With the same degree of success one can declare the built-in -> operator "useless" because of its equivalence to *+. combination.
You can have the same behavior as in C, nobody forces you to use the additional "class" features. So if you understand their purpose in C, it should be understandable in C++ as well (the "C-like" portion at least).
As Joachim Pileborg already pointed out, classes and structures are almost the same thing in C++.
I would, however, recommend to use struct for "dumb" data holders with public members and class for properly encapsulated classes as a style convention.

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

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.

Is it always evil to have a struct with methods?

I've just been browsing and spotted the following...
When should you use a class vs a struct in C++?
The consensus there is that, by convention, you should only use struct for POD, no methods, etc.
I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions as members. The struct should still be POD by most of the usual rules - in particular it must be safe to copy using memcpy. It must have all member data public. But it still makes sense to me to have helper functions as members. I wouldn't even necessarily object to a private method, though I don't recall ever doing this myself. And although it breaks the normal POD rules, I wouldn't object to a struct having constructors, provided they were just initialise-a-few-fields constructors (overriding assignment or destructors would definitely be against the rules).
To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction. The logical place to put the helper functions for your collection-of-fields may well be within the struct.
I even think I once read some advice along these lines, though I don't remember where.
Is this against accepted best practice?
EDIT - POD (Plain Old Data) is misrepresented by this question. In particular, a struct can be non-POD purely because a member is non-POD - e.g. an aggregate with a member of type std::string. That aggregate must not be copied with memcpy. In case of confusion, see here.
For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.
EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.
As far as the language is concerned, it doesn't matter, except for default private vs. public access. The choice is subjective.
I'd personally say use struct for PODs, but remember that "POD" doesn't mean "no member functions". It means no virtual functions, constructors, destructor, or operator=.
Edit: I also use structs for simple public-access aggregates of data, even if their members aren't PODs.
I tend to use struct a lot.
For the "traditional" OOP classes (the ones that represent a specific "thing"), I tend to use class simply because it's a common convention.
But most of my classes aren't really OOP objects. They tend to be functors, and traits classes and all sorts of other more abstract code concepts, things I use to express myself, rather than modelling specific "things". And those I usually make struct. It saves me having to type the initial public:, and so it makes the class definition shorter and easier to get an overview of.
I also lean towards making larger, more complex classes class. Except this rarely affects anything, because I lean even more towards refactoring large, complex classes... And then I'm left with small simple ones, which might be made struct's.
But in either case, I'd never consider it "evil". "Evil" is when you do something that actively obfuscates your code, or when you make something far more complex than necessary.
But every C++ programmer knows that struct and class mean virtually the same thing. You're not going to be confused for long because you see a struct Animal {...}; You know that it's a class designed to model an animal. So no, it's not "evil" no matter which way you do it.
When I have control over the style guides, everything is defined as a struct. Historically, I wanted all my objects to be one or the other, since I was taught it was undefined behavior to forward declared a struct as a class, and vice versa (I'm not sure if this was ever actually true, its just what I was told). And really, struct has the more reasonable default state.
I still do the same because I've never been convinced of the value of using it as a form of documentation. If you need to convey that an object only has public members, or doesn't have any member functions, or whatever arbitrary line you chose to draw between the two, you have actual documentation available for that. Since you never actually use the struct or class keyword when using the type, you would need to go hunting for the definition anyhow if you want the information. And with everybody having their own opinion on what struct actually means, its usefulness as self-documentation is reduced. So I shoot for consistency: everything as one or the other. In this case, struct.
Its not a popular way of doing things, to say the least. Fortunately for everybody involved, I very rarely have control over the coding standards.
I use a struct whenever I need an aggregate of public data members (as opposed to class, which I use for types that come with a certain level of abstractions and have their data private).
Whether or not such a data aggregate has member functions doesn't matter to me. In fact, I rarely ever write a struct without also providing at least one constructor for it.
You said, "To me a struct is intuitively a collection of fields - a data structure node or whatever". What you are describing is Plain Old Data. The C++ standard does have an opinion of what POD means with respect to C++ language features. I suggest that, where possible, you adopt the meaning of POD used in C++0x.
I need to find a reference for this, but I thought that, as far as type definitions are concerned, the keywords "struct" and "class" are to be synonyms in C++0x. The only difference being that class defaults to private members, while a struct defaults to public. This means that you'll never see complier error messages like "Type X first seen using struct, now seen using class." once we're all using C++0x.
I think that it is wrong to have strict rules on when to use class and when to use struct. If consistency is important to you, the go ahead and make a coding standard that has what ever sort of rules you like. Just make sure everyone knows that your coding standard relates to how you want you code to look - it doesn't relate to the underlying language features at all.
Maybe to give an example where I break all your rules, you say "To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction." When I want to write a class that implements some abstraction, I define the interface as a struct with pure virtual methods (egad!) - this is exposed in a header, as too is a factory method to construct my concrete class. The concrete class is not exposed i a public header at all. Since the concrete class is a secret, it can be implemented however I like and it makes no difference to external code.
I'd suggest that if you think that the keywords struct and class have any relation to the concept of POD, then you're not understanding C++ yet.