C/C++ Struct vs Class - c++

After finishing my C++ class it seemed to me the structs/classes are virtually identical except with a few minor differences.
I've never programmed in C before; but I do know that it has structs. In C is it possible to inherit other structs and set a modifier of public/private?
If you can do this in regular C why in the world do we need C++? What makes classes different from a struct?

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.

Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C

I'm going to add to the existing answers because modern C++ is now a thing and official Core Guidelines have been created to help with questions such as these.
Here's a relevant section from the guidelines:
C.2: Use class if the class has an invariant; use struct if the data members can vary independently
An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.
If all data members can vary independently of each other, no invariant is possible.
If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.
Enforcement
Look for structs with all data private and classes with public members.
The code examples given:
struct Pair { // the members can vary independently
string name;
int volume;
};
// but
class Date {
public:
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
// ...
private:
int y;
Month m;
char d; // day
};
Classes work well for members that are, for example, derived from each other or interrelated. They can also help with sanity checking upon instantiation. Structs work well for having "bags of data", where nothing special is really going on but the members logically make sense being grouped together.
From this, it makes sense that classes exist to support encapsulation and other related coding concepts, that structs are simply not very useful for.

It's not possible to define member functions or derive structs from each other in C.
Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.

One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

Since nobody has mentioned it yet, there is actually another difference besides the default visibility. It turns out that class and struct are actually different things in MSVC.
class Vector2;
struct Vector2 {
double x;
double y;
};
This is 1 symbol on most compilers, but 2 different symbols on MSVC. Just this code by itself does compile fine. However, if you try to use it in more complex scenarios you will run into errors where this does not compile on MSVC because it gets confused about the symbols.

Related

Difference between using structures with methods and with functions and classes? [duplicate]

This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 2 months ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
In what scenarios is it better to use a struct vs a class 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.
As everyone else notes there are really only two actual language differences:
struct defaults to public access and class defaults to private access.
When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.
But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:
class X
{
public:
// ...
};
struct X
{
// ...
};
(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)
There are lots of misconceptions in the existing answers.
Both class and struct declare a class.
Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.
But, beyond syntax, the only reason to choose one over the other is convention/style/preference.
Some people like to stick with the struct keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.
Similarly, some people like to use the class keyword for classes with member functions and private data, because it says "class" on it and therefore looks like examples from their favourite book on object-oriented programming.
The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.
The following two classes are absolutely equivalent in every way except their name:
struct Foo
{
int x;
};
class Bar
{
public:
int x;
};
You can even switch keywords when redeclaring:
class Foo;
struct Bar;
(although this breaks Visual Studio builds due to non-conformance, so that compiler will emit a warning when you do this.)
and the following expressions both evaluate to true:
std::is_class<Foo>::value
std::is_class<Bar>::value
Do note, though, that you can't switch the keywords when redefining; this is only because (per the one-definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange const int member; with int const member;, and has nothing to do with the semantics of class or struct.
The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:
struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare());
From the C++ FAQ Lite:
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.
You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:
// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif
// Put your C struct's here
struct foo
{
...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;
// Put your C API functions here
void bar(foo *fun);
#ifdef __cpp
}
#endif
Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.
One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.
typedef struct
{
int messageId;
int messageCounter;
int messageData;
} tMessageType;
void processMessage(unsigned char *rawMessage)
{
tMessageType *messageFields = (tMessageType *)rawMessage;
printf("MessageId is %d\n", messageFields->messageId);
}
Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.
As every one says, the only real difference is the default access. But I particularly use struct when I don't want any sort of encapsulation with a simple data class, even if I implement some helper methods. For instance, when I need something like this:
struct myvec {
int x;
int y;
int z;
int length() {return x+y+z;}
};
To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.
I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.
For C++, there really isn't much of a difference between structs and classes. The main functional difference is that members of a struct are public by default, while they are private by default in classes. Otherwise, as far as the language is concerned, they are equivalent.
That said, I tend to use structs in C++ like I do in C#, similar to what Brian has said. Structs are simple data containers, while classes are used for objects that need to act on the data in addition to just holding on to it.
Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.
If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as #ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.
Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:
template <typename T> struct type_traits {
typedef T type;
typedef T::iterator_type iterator_type;
...
};
...But that's really just taking advantage of struct's default protection level being public...
As others have pointed out
both are equivalent apart from default visibility
there may be reasons to be forced to use the one or the other for whatever reason
There's a clear recommendation about when to use which from Stroustrup/Sutter:
Use class if the class has an invariant; use struct if the data members can vary independently
However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }).
It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.
Both struct and class are the same under the hood though with different defaults as to visibility, struct default is public and class default is private. You can change either one to be the other with the appropriate use of private and public. They both allow inheritance, methods, constructors, destructors, and all the rest of the goodies of an object oriented language.
However one huge difference between the two is that struct as a keyword is supported in C whereas class is not. This means that one can use a struct in an include file that can be #include into either C++ or C so long as the struct is a plain C style struct and everything else in the include file is compatible with C, i.e. no C++ specific keywords such as private, public, no methods, no inheritance, etc. etc. etc.
A C style struct can be used with other interfaces which support using C style struct to carry data back and forth over the interface.
A C style struct is a kind of template (not a C++ template but rather a pattern or stencil) that describes the layout of a memory area. Over the years interfaces usable from C and with C plug-ins (here's looking at you Java and Python and Visual Basic) have been created some of which work with C style struct.
An advantage of struct over class is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keyword class useless.
Here is another reason for using only struct and never class. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to a class? Everywhere?
Distinguishing between structs and classes is just too much hassle getting into the way of doing what we should be doing - programming. Like so many of C++'s problems it arises out of the strong desire for backwards compatibility.
They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class
The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.
In practice, I've always used structs as data holders and classes as objects.
Class.
Class members are private by default.
class test_one {
int main_one();
};
Is equivalent to
class test_one {
private:
int main_one();
};
So if you try
int two = one.main_one();
We will get an error: main_one is private because its not accessible. We can
solve it by initializing it by specifying its a public ie
class test_one {
public:
int main_one();
};
Struct.
A struct is a class where members are public by default.
struct test_one {
int main_one;
};
Means main_one is private ie
class test_one {
public:
int main_one;
};
I use structs for data structures where the members can take any value, it's
easier that way.
After years of programming in C++, my main language, I come to the dead conclusion that this is another one of C++ dumb feature.
There is no real difference between the two, and no reason why I should spend extra time deciding whether I should define my entity as a struct or a class.
To answer this question, feel free to always define your entity as a struct. Members will be public by default which is the norm. But even more importantly, inheritance will be public by default. Protected inheritance, and even worse, private inheritance, are the exceptions.
I have never had a case where private inheritance was the right thing to do. Yes I tried to invent problems to use private inheritance but it didn't work. And Java, the role model of Object Oriented programming defaults to public inheritance if you don't use the accessor keywords. And by the way, Java doesn't allow accessor keywords on inherited classes, they can only be publicly inherited. So you can see, the cpp team really fell down here.
Another frustrating thing about this, is that if you define as a class and declare as a struct you get compilation warning. As though this is something that impacted the performance or accuracy of your program. One answer also noted that MSVC may propogate a compiler error instead.
Those persons that use classes when it is raining and structs when it is shining are doing so based on what they have been taught. It's not something they discovered to be true. Java does not have a pair of names for classes, and only have the class keyword. If you want a data structure, simply make all your members public and don't add functions. This works in Java and I don't see any problem. What's the problem? You need 4 or 5 characters of BOM code to determine how to interpret the context of a class entity.
they're the same thing with different defaults (private by default for class, and public by default for struct), so in theory they're totally interchangeable.
so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.
Structs by default have public access and classes by default have private access.
Personally I use structs for Data Transfer Objects or as Value Objects. When used as such I declare all members as const to prevent modification by other code.
Just to address this from a C++20 Standardese perspective (working from N4860)...
A class is a type. The keywords "class" and "struct" (and "union") are - in the C++ grammar - class-keys, and the only functional significance of the choice of class or struct is:
The class-key determines whether ... access is public or private by default (11.9).
Data member default accessibility
That the class keyword results in private-by-default members, and `struct keyword results in public-by-default members, is documented by the examples in 11.9.1:
class X {
int a; // X::a is private by default: class used
...vs...
struct S {
int a; // S::a is public by default: struct used
Base class default accessibility
1.9 also says:
In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.
Circumstances where consistent use of struct or class is required...
There's a requirement:
In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration (9.2.8.3).
...in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (9.7.1), the union class-key shall be used to refer to a union (11.5), and either the class or struct class-key shall be
used to refer to a non-union class (11.1).
The following example (of when consistency is not required) is provided:
struct S { } s;
class S* p = &s; // OK
Still, some compilers may warn about this.
Interestingly, while the types you create with struct, class and union are all termed "classes", we have...
A standard-layout struct is a standard layout class defined with the class-key struct or the class-key class.
...so in Standardese, when there's talk of a standard-layout struct it's using "struct" to imply "not a union"s.
I'm curious if there are similar use of "struct" in other terminology, but it's too big a job to do an exhaustive search of the Standard. Comments about that welcome.
Technically both are the same in C++ - for instance it's possible for a struct to have overloaded operators etc.
However :
I use structs when I wish to pass information of multiple types simultaneously
I use classes when the I'm dealing with a "functional" object.
Hope it helps.
#include <string>
#include <map>
using namespace std;
struct student
{
int age;
string name;
map<string, int> grades
};
class ClassRoom
{
typedef map<string, student> student_map;
public :
student getStudentByName(string name) const
{ student_map::const_iterator m_it = students.find(name); return m_it->second; }
private :
student_map students;
};
For instance, I'm returning a struct student in the get...() methods over here - enjoy.
When would you choose to use struct
and when to use class in C++?
I use struct when I define functors and POD. Otherwise I use class.
// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
bool operator()(int first, int second)
{ return first < second; }
};
class mycompare : public std::binary_function<int, int, bool>
{
public:
bool operator()(int first, int second)
{ return first < second; }
};
I use structs when I need to create POD type or functor.
All class members are private by default and all struct members are public by default.
Class has default private bases and Struct has default public bases. Struct in case of C cannot have member functions where as in case of C++ we can have member functions being added to the struct. Other than these differences, I don't find anything surprising about them.
I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.
Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.
Technically there is no big difference between class and struture except default accessibility.
More over it depends on programming style how you use it.
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I thought that Structs was intended as a Data Structure (like a multi-data type array of information) and classes was inteded for Code Packaging (like collections of subroutines & functions)..
:(
I never use "struct" in C++.
I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.
It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.
E.g.
class PublicInputData {
//data members
};

Cast a simple (c++) struct to another derived (c++) struct containing same datatypes [duplicate]

If I have a class as follows
class Example_Class
{
private:
int x;
int y;
public:
Example_Class()
{
x = 8;
y = 9;
}
~Example_Class()
{ }
};
And a struct as follows
struct
{
int x;
int y;
} example_struct;
Is the structure in memory of the example_struct simmilar to that in Example_Class
for example if I do the following
struct example_struct foo_struct;
Example_Class foo_class = Example_Class();
memcpy(&foo_struct, &foo_class, sizeof(foo_struct));
will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ?
The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.
I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.
The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean?
A class or struct is POD if:
All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such
It has no user-defined constructors, assignment operators or destructors
It has no virtual functions
It has no base classes
About the only "C++-isms" allowed are non-virtual member functions, static members and member functions.
Since your class has both a constructor and a destructor, it is formally speaking not of POD type, so the guarantee does not hold. (Although, as others have mentioned, in practice the two layouts are likely to be identical on any compiler that you try, so long as there are no virtual functions).
See section [26.7] of the C++ FAQ Lite for more details.
Is the structure in memory of the example_struct simmilar to that in Example_Class
The behaviour isn't guaranteed, and is compiler-dependent.
Having said that, the answer is "yes, on my machine", provided that the Example_Class contains no virtual method (and doesn't inherit from a base class).
In the case you describe, the answer is "probably yes". However, if the class has any virtual functions (including virtual destructor, which could be inherited from a base class), or uses multiple inheritance then the class layout may be different.
To add to what other people have said (eg: compiler-specific, will likely work as long as you don't have virtual functions):
I would highly suggest a static assert (compile-time check) that the sizeof(Example_class) == sizeof(example_struct) if you are doing this. See BOOST_STATIC_ASSERT, or the equivalent compiler-specific or custom construction. This is a good first-line of defense if someone (or something, such as a compiler change) modifies the class to invalidate the match. If you want extra checking, you can also runtime check that the offsets to the members are the same, which (together with the static size assert) will guarantee correctness.
In the early days of C++ compilers there were examples when compiler first changes struct keywords with class and then compiles. So much about similarities.
Differences come from class inheritance and, especially, virtual functions. If class contains virtual functions, then it must have a pointer to type descriptor at the beginning of its layout. Also, if class B inherits from class A, then class A's layout comes first, followed by class B's own layout.
So the precise answer to your question about just casting a class instance to a structure instance is: depends on class contents. For particular class which has methods (constructor and non-virtual destructor), the layout is probably going to be the same. Should the destructor be declared virtual, the layout would definitely become different between structure and class.
Here is an article which shows that there is not much needed to do to step from C structures to C++ classes: Lesson 1 - From Structure to Class
And here is the article which explains how virtual functions table is introduced to classes that have virtual functions: Lesson 4 - Polymorphism
Classes & structs in C++ are the equivalent, except that all members of a struct are public by default (class members are private by default). This ensures that compiling legacy C code in a C++ compiler will work as expected.
There is nothing stopping you from using all the fancy C++ features in a struct:
struct ReallyAClass
{
ReallyAClass();
virtual !ReallAClass();
/// etc etc etc
};
Why not explicitly assign the class's members to the struct's when you want to pass the data to C? That way you know your code will work anywhere.
You probably just derive the class from the struct, either publicly or privately. Then casting it would resolve correctly in the C++ code.

C++ typedef struct vs class

I am not very familiar with C++ , and while I am trying some test programms I came to a question regarding the best if I may say so way to define some primitive elements in C++ code.
Let's take a class that describes rectangles. It would create them, draw them , rotate, resize, etc... now in most cases we have to deal with points on the canvas.
The rectangle its self is described by 2 points: Upper Left and Lower Right corner.
Also in order to Rotate it, you need an angle, and a point(anchor point).
Or maybe to move it you need a new anchor point for the given rectangle. I guess I made my point in using points .
So what is more efficient ? to define this primitive point as a class or as a struct?
class cPoint
{
public:
int X;
int Y;
};
or
typedef struct
{
int X;
int Y;
}sPoint;
Niether are more efficient. On a technical level, there is no difference between a class and a struct aside from default visibility of members (public in struct, private in class) and default inheritance model (public in struct, private in class).
They typedef struct {} name model is not idiomatic in C++. In fact, it's an abomination -- a holdover from C. Don't use this model. Use this struct name {}; instead. Using the typedef struct {} name; model doesn't gain you anything in C++ (it was needed in C), and may cost you sojmething in terms of maintainability. For instance, it might be harder to grep for typedef struct declarations. But since it doesn't gain you anything by doing this, there's no compelling reason not to simply do struct name {}; in C++.
Aside from technical issues, the differences between struct and class are semantic ones. It is traditional and expected that objects declared as structs are simple objects which consist of only public: data members (so-called PODs). If it has private or protected data, is expected to be derived from, or has any methods, it is declared as a class.
This guideline is open to interpretation, and is just that -- a guideline. There is nothing to prevent you from declaring an abstract base class as a struct, for example. However you may want to consider following this guideline in order to follow the Principle of Least Surprise, making your code easier to understand and maintain.
Both are nearly equivalent. More precisely, struct { is the same as class {public:
An optimizing compiler would probably generate exactly the same code. Use MELT or simply pass -fdump-tree-all (beware, that option produces hundreds of dump files) to g++ (assuming you use a recent GCC compiler) -preferably with some optimization like -O - to find out (or look at the produced assembler code with g++ -O -fverbose-asm -S ...)
typedef struct is actually the C way to do this. In C++ the two versions would look very similar: Your class as written, and the struct as follows:
struct sPoint
{
int X;
int Y;
};
The two forms are functionally identical but you can provide your future maintainers with significant information by picking and sticking to some convention about how they're used. For example one approach is that if you intend to make the data elements private and give it useful methods (for example if you use inline accessors you can insert print calls every time the methods are used) then by all means make it a class. If you intend to have the data be public and access them as members then make it a struct.
There's no performance difference between a class and a struct
A class defaults to private access, whilst a struct defaults to public access. If interoperability with C is an issue for you then you'll have to use struct, and obviously it can't have any member functions.
As an aside, there's no std::is_struct in the standard library. Instead the std::is_class method returns true if the type is a class or a structure.
Simply put, the first way is more C++, and the second way is more C. Both work, while the first way is more 'standard' now.
A struct in C++ is like a class that would have public members by default*
There is no other formal difference, though your code would probably look confusing if you started using structs as classes, especially the inheritance mechanisms where data privacy is a major benefit.
If you are about to declare private/protected members, there is really little point in using a struct, though your code will still be 100% legal.
*including inherited members, since the zealots and nitpickers around seem to think the point is of a capital importance and only ignorant heatens would fail to mention it.
Except for the fact that this fine doctrine point is defined (or rather hinted, since the inference that base classes are simply defining inherited members is left to the sagacity of the reader) in another verse of the Stoustrup Holy Bible, there is really nothing to fuss about IMHO.
To properly declare the struct in your example, use
struct sPoint {
int X;
int Y;
};
In general, structs and classes in C++ are identical, except that data is public in a struct by default. The other difference is that the struct keyword cannot be used as the type in a template, although a struct can be used as the parameter.
There is a more thorough discussion here: C++ - struct vs. class
technically, struct{} and class{} are the same.
they differ on semantic level, with different member visibility.
struct{...} is equivalent to class{public:...}
And, it is also legal to declare a class using struct keyword. (add member functions, access specifier to struct{})
Generally, using struct for Plain-Old-Data (POD) type, class for Object-Oriented type to improve readability.
typedef struct{} should only be used to hide implementation detail(eg: supply a close-source library to users)
From my opinion, in your case, using struct is better, because Point's member need to be modified directly by other code.

c++ struct OO vs class OO [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
class and struct in c++
It looks like that struct can has constructor and destructor and members, and looks very simple, so can we use struct instead class, if not, when shall we use struct with functions when shall we use class ?
https://github.com/developmentseed/node-sqlite3/blob/master/src/database.h#L32
struct Baton {
uv_work_t request;
Database* db;
Persistent<Function> callback;
int status;
std::string message;
Baton(Database* db_, Handle<Function> cb_) :
db(db_), status(SQLITE_OK) {
db->Ref();
uv_ref(uv_default_loop());
request.data = this;
callback = Persistent<Function>::New(cb_);
}
virtual ~Baton() {
db->Unref();
uv_unref(uv_default_loop());
callback.Dispose();
}
};
struct OpenBaton : Baton {
std::string filename;
int mode;
OpenBaton(Database* db_, Handle<Function> cb_, const char* filename_, int mode_) :
Baton(db_, cb_), filename(filename_), mode(mode_) {}
};
There's absolutely no technical reason to prefer one over the other, but I've noticed a certain convention regarding the use of class or struct.
If your datatype is something that is meant to be used by other parts of your program (ie. it's part of the 'interface'), then usually people make it a class to indicate its importance. If the datatype is used only in the implementation of a function or a class and it is not visible outside of a certain scope, then make it a struct.
These are some very rought guidelines, but no one will complain if you don't follow them.
Edit: In C++ there's no real difference between the two, but other newer languages that are inspired by C++ have actually made struct and class different. In C# and in D, for example, class and struct are both used to define datatypes, but they are not the same: struct is implemented such that it should be used for 'small' types.
The only difference is the default access-level (private for a class, public for a struct). Other than that, they are completely interchangeable. You should decide which one you like better, and use that all the time (consistency makes your code more readable).
when shall we use struct with functions when shall we use class ?
It is completely your choice.
There is nothing that one can do with classes and not with structures in C++.
Only difference between structure and class are:
access specifier defaults to private for class and public for struct
inheritance defaults to private for class and public for struct
So just use the one of your choice and stick to using it consistently, do not mix classes and structures.
While as stated by other struct & class does not have any difference besides default access level. However, it's common practice to use structs mostly for data aggregation, as that is what structs are reduced to in C. For example user defined PODs are almost always created as structs in my experience.
The only difference between class and struct is the default accessibility to its members and base classes. For struct, it is public and for class, it is private.
As others have said, the main difference is the default access level of member data and functions, namely private for class and public for structs. The same goes for default inheritance access levels: private for classes and public for structs.
As for when to use which, that is a matter of what is normal for the company to do. In my experience, most companies, and indeed individuals, use structs to hold packets of pure data and classes for storing a collection of functions that operate on its own data and/or structs.
This method is a throwback to C programming where structs can only store data and not functions and so most people like to stick to this definition in C++ too.
Note that it is common to use structs for functors, which would seem to break consistency through the code of structs not containing functions, but since functors usually only overload the () operator we retain some form of consistency anyway. Plus, it saves us having to type public for one function and/or inherited structures... Oh the typing we allow ourselves to avoid ;)
A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

Structure of a C++ Object in Memory Vs a Struct

If I have a class as follows
class Example_Class
{
private:
int x;
int y;
public:
Example_Class()
{
x = 8;
y = 9;
}
~Example_Class()
{ }
};
And a struct as follows
struct
{
int x;
int y;
} example_struct;
Is the structure in memory of the example_struct simmilar to that in Example_Class
for example if I do the following
struct example_struct foo_struct;
Example_Class foo_class = Example_Class();
memcpy(&foo_struct, &foo_class, sizeof(foo_struct));
will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ?
The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.
I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.
The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean?
A class or struct is POD if:
All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such
It has no user-defined constructors, assignment operators or destructors
It has no virtual functions
It has no base classes
About the only "C++-isms" allowed are non-virtual member functions, static members and member functions.
Since your class has both a constructor and a destructor, it is formally speaking not of POD type, so the guarantee does not hold. (Although, as others have mentioned, in practice the two layouts are likely to be identical on any compiler that you try, so long as there are no virtual functions).
See section [26.7] of the C++ FAQ Lite for more details.
Is the structure in memory of the example_struct simmilar to that in Example_Class
The behaviour isn't guaranteed, and is compiler-dependent.
Having said that, the answer is "yes, on my machine", provided that the Example_Class contains no virtual method (and doesn't inherit from a base class).
In the case you describe, the answer is "probably yes". However, if the class has any virtual functions (including virtual destructor, which could be inherited from a base class), or uses multiple inheritance then the class layout may be different.
To add to what other people have said (eg: compiler-specific, will likely work as long as you don't have virtual functions):
I would highly suggest a static assert (compile-time check) that the sizeof(Example_class) == sizeof(example_struct) if you are doing this. See BOOST_STATIC_ASSERT, or the equivalent compiler-specific or custom construction. This is a good first-line of defense if someone (or something, such as a compiler change) modifies the class to invalidate the match. If you want extra checking, you can also runtime check that the offsets to the members are the same, which (together with the static size assert) will guarantee correctness.
In the early days of C++ compilers there were examples when compiler first changes struct keywords with class and then compiles. So much about similarities.
Differences come from class inheritance and, especially, virtual functions. If class contains virtual functions, then it must have a pointer to type descriptor at the beginning of its layout. Also, if class B inherits from class A, then class A's layout comes first, followed by class B's own layout.
So the precise answer to your question about just casting a class instance to a structure instance is: depends on class contents. For particular class which has methods (constructor and non-virtual destructor), the layout is probably going to be the same. Should the destructor be declared virtual, the layout would definitely become different between structure and class.
Here is an article which shows that there is not much needed to do to step from C structures to C++ classes: Lesson 1 - From Structure to Class
And here is the article which explains how virtual functions table is introduced to classes that have virtual functions: Lesson 4 - Polymorphism
Classes & structs in C++ are the equivalent, except that all members of a struct are public by default (class members are private by default). This ensures that compiling legacy C code in a C++ compiler will work as expected.
There is nothing stopping you from using all the fancy C++ features in a struct:
struct ReallyAClass
{
ReallyAClass();
virtual !ReallAClass();
/// etc etc etc
};
Why not explicitly assign the class's members to the struct's when you want to pass the data to C? That way you know your code will work anywhere.
You probably just derive the class from the struct, either publicly or privately. Then casting it would resolve correctly in the C++ code.