What is the order of fields in an inherited class? - c++

struct A {int a;};
struct B : public A {int b;};
B b;
Does the Standard guarantee how are the fields ordered in memory i.e. does a come before b and is there any padding?
Use case. I have class Specification and class Command. The command objects include a specification in them, as well as some additional information. I want to be able to use an object of either type when a Specification is required.

You asked:
Does the Standard guarantee how are the fields ordered in memory i.e. does a come before b and is there any padding?
The standard does not make any such guarantee. It leaved those details to the implementation. From the C++ Draft Standard (N3337):
10 Derived Classes
5 The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified. [ Note: a derived class and its base class subobjects can be represented by a directed acyclic graph (DAG) where an arrow means “directly derived from.” A DAG of subobjects is often referred to as a “subobject
lattice.”
Base
^
|
Derived1
^
|
Derived2
6 The arrows need not have a physical representation in memory. — end note ]
While the standard does not guarantee it, I haven't seen an implementation that does not do what you are expecting. There may be some in the wild but I haven't seen them.

This sounds like what you want is polymorphism (either create a base class Specification or just some interface class, i.e. an abstract base class), whatever better fits your use case. Pretty much what you're doing already:
class Specification {
int a;
}
class Command : public Specificaion {
// int a; is essentially here, inherited from Specification
int b;
}
// later on:
Specification *mySpec = new Specification();
mySpec->a = 5; // valid
delete mySpec;
mySpec = new Command();
mySpec->a = 60; // valid as well
As long as you're working with pointers of the base class, you're basically going "from top to bottom" when looking up members. It's a bit more complicated than that, but since you're obviously using C++, you shouldn't just try casting unrelated types and hope that members are aligned the same way. If you need some way to read/write the classes to/from files, create some member to do the serialization in a clearly defined way.

Does 'a' come before 'b' - YES
Is there any padding? - Depends on compiler/pragma/alignment settings. And it depends on compiler/IDE how to setup packing/alignment (although new standards have some new keywords).

Related

Why does changing "class" to "struct" for a hasher work for `unordered_map<std::pair<int,int>, int, pair_hasher>`? [duplicate]

This question was already asked in the context of C#/.Net.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
I'll start with an obvious difference:
If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.
I'm sure there are other differences to be found in the obscure corners of the C++ specification.
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.
Quoting The C++ FAQ,
[7.8] What's the difference between
the keywords struct and class?
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.
It's worth remembering C++'s origins in, and compatibility with, C.
C has structs, it has no concept of encapsulation, so everything is public.
Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.
On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).
So a new keyword, class was introduced to be exactly like a struct, but private by default.
If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.
In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.
Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.
According to Stroustrup in the C++ Programming Language:
Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
Functionally, there is no difference other than the public / private
Members of a class are private by default and members of struct are public by default.
For example program 1 fails in compilation and program 2 works fine.
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error because inheritance is private
getchar();
return 0;
}
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine because inheritance is public
getchar();
return 0;
}
STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)
Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.
In effect, structs are about data, classes are about code.
However, you do need to understand that these are merely abstractions. It's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.
Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
The difference between class and struct is a difference between keywords, not between data types. This two
struct foo : foo_base { int x;};
class bar : bar_base { int x; };
both define a class type. The difference of the keywords in this context is the different default access:
foo::x is public and foo_base is inherited publicly
bar::x is private and bar_base is inherited privately
The members of a structure are public by default, the members of class are private by default.
Default inheritance for Structure from another structure or class is public.Default inheritance for class from another structure or class is private.
class A{
public:
int i;
};
class A2:A{
};
struct A3:A{
};
struct abc{
int i;
};
struct abc2:abc{
};
class abc3:abc{
};
int _tmain(int argc, _TCHAR* argv[])
{
abc2 objabc;
objabc.i = 10;
A3 ob;
ob.i = 10;
//A2 obja; //privately inherited
//obja.i = 10;
//abc3 obss;
//obss.i = 10;
}
This is on VS2005.
Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.
One other thing to note, if you updated a legacy app that had structs to use classes you might run into the following issue:
Old code has structs, code was cleaned up and these changed to classes.
A virtual function or two was then added to the new updated class.
When virtual functions are in classes then internally the compiler will add extra pointer to the class data to point to the functions.
How this would break old legacy code is if in the old code somewhere the struct was cleared using memfill to clear it all to zeros, this would stomp the extra pointer data as well.
Another main difference is when it comes to Templates. As far as I know, you may use a class when you define a template but NOT a struct.
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
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.
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.
You can use template<class T> but not template<struct T>.
Note also that the C++ standard allows you to forward-declare a type as a struct, and then use class when declaring the type and vice-versa. Also, std::is_class<Y>::value is true for Y being a struct and a class, but is false for an enum class.
Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php
So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.
It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.
ISO IEC 14882-2003
9 Classes
§3
A structure is a class defined with
the class-key struct; its members
and base classes (clause 10) are
public by default (clause 11).
The other answers have mentioned the private/public defaults, (but note that a struct is a class is a struct; they are not two different items, just two ways of defining the same item).
What might be interesting to note (particularly since the asker is likely to be using MSVC++ since he mentions "unmanaged" C++) is that Visual C++ complains under certain circumstances if a class is declared with class and then defined with struct (or possibly the other way round), although the standard says that is perfectly legal.
. In classes all the members by default are private but in structure
members are public by default.
There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide.
Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should
typically be used for grouping data.
The class default access type is private, and the default mode for
inheritance is private. A class should be used for grouping data and
methods that operate on that data.
In short, the convention is to use struct when the purpose is to
group data, and use classes when we require data abstraction and,
perhaps inheritance.
In C++ structures and classes are passed by value, unless explicitly
de-referenced. In other languages classes and structures may have
distinct semantics - ie. objects (instances of classes) may be passed
by reference and structures may be passed by value. Note: There are
comments associated with this question. See the discussion page to
add to the conversation.
While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.
This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).
There exists also unwritten rule that tells:
If data members of class have no association with itself, use struct.
If value of data member depends on another value of data member, use class.
f.e
class Time
{
int minutes;
int seconds;
}
struct Sizes
{
int length;
int width;
};
You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .
√ CONSIDER defining a struct instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
X AVOID defining a struct unless the type has all of
the following characteristics:
It logically represents a single value,
similar to primitive types (int, double, etc.).
It has an instance
size under 16 bytes.
It is immutable.
It will not have to be boxed
frequently.
The difference between struct and class keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct or union is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct for data and class for code sake. For more information contact other sources.
Out of all these factors,it can be concluded that concept Class is highly suitable to represent real world objects rather than "Structures".Largely because OOP concepts used in class are highly practical in explaining real world scenarios therefore easier to merge them to reality.For an example,default inheritance is public for structs but if we apply this rule for real world,it's ridiculous.But in a class default inheritance is private which is more realistic.
Anyways,what i need to justify is Class is a much broader,real world applicable concept whereas Structure is a primitive Concept with poor internal organization(Eventhough struct follows OOP concepts,they have a poor meaning)
Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.
When developing large project with tons of people without class, you may finally get complicated coupled code because everybody use whatever functions and data they want. class provides permission controls and inherents to enhance decoupling and reusing codes.
If you read some software engineering principles, you'll find most standards can not be implemented easily without class. for example:
http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
BTW, When a struct allocates a crunch of memory and includes several variables, value type variables indicates that values are embbeded in where struct is allocated. In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.
The main difference between structure and class keyword in oops is that, no public and private member declaration present in structure.and the data member and member function can be defined as public, private as well as protected.
The main difference between struct and class is that in struct you can only declare data variables of different data types while in class you can declare data variables,member functions and thus you can manipulate data variables through functions.
-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it .
while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..
But it depennds on the programmer which way he/she finds suitable...according to me i prefer class everytime just because it supports OOPs and thats the reason it is implemented in almost every languages and its the wonderful feature of all time programming ;-)
And yeah the most unforgotten difference i forgot to mention is that class supports data hiding and also supports operations that are performed on built in data types while struct doesnt !
I found an other difference. if you do not define a constructor in a class, the compiler will define one. but in a struct if you do not define a constructor, the compiler do not define a constructor too. so in some cases that we really do not need a constructor, struct is a better choice (performance tip).
and sorry for my bad English.
Classes are Reference types and Structures are Values types.
When I say Classes are reference types,
basically they will contain the address of an instance variables.
For example:
Class MyClass
{
Public Int DataMember; //By default, accessibility of class data members
//will be private. So I am making it as Public which
//can be accessed outside of the class.
}
In main method,
I can create an instance of this class using new operator that allocates memory for this class
and stores the base address of that into MyClass type variable(_myClassObject2).
Static Public void Main (string[] arg)
{
MyClass _myClassObject1 = new MyClass();
_myClassObject1.DataMember = 10;
MyClass _myClassObject2 = _myClassObject1;
_myClassObject2.DataMember=20;
}
In the above program,
MyClass _myClassObject2 = _myClassObject1;
instruction indicates that both variables of type MyClass
myClassObject1
myClassObject2
and will point to the same memory location.
It basically assigns the same memory location into another variable of same type.
So if any changes that we make in any one of the objects type MyClass will have an effect on another
since both are pointing to the same memory location.
"_myClassObject1.DataMember = 10;" at this line both the object’s data members will contain the value of 10.
"_myClassObject2.DataMember = 20;" at this line both the object’s data member will contains the value of 20.
Eventually, we are accessing datamembers of an object through pointers.
Unlike classes, structures are value types.
For example:
Structure MyStructure
{
Public Int DataMember; //By default, accessibility of Structure data
//members will be private. So I am making it as
//Public which can be accessed out side of the structure.
}
Static Public void Main (string[] arg)
{
MyStructure _myStructObject1 = new MyStructure();
_myStructObject1.DataMember = 10;
MyStructure _myStructObject2 = _myStructObject1;
_myStructObject2.DataMember = 20;
}
In the above program,
instantiating the object of MyStructure type using new operator and
storing address into _myStructObject variable of type MyStructure and
assigning value 10 to data member of the structure using "_myStructObject1.DataMember = 10".
In the next line,
I am declaring another variable _myStructObject2 of type MyStructure and assigning _myStructObject1 into that.
Here .NET C# compiler creates another copy of _myStructureObject1 object and
assigns that memory location into MyStructure variable _myStructObject2.
So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue.
That’s why we are saying Structures are value types.
So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.
Classes will support an Inheritance whereas Structures won’t.
How are we saying that?
And what is the reason behind that?
The answer is Classes.
It can be abstract, sealed, static, and partial and can’t be Private, Protected and protected internal.
There are 3 basic difference between structure and class
1St- memory are reserved for structure in stack memory (which is near to programming language )whether for class in stack memory are reserved for only reffrence and actual memory are reserved in heap memory.
2Nd - By default structure treat as a public whether class treat as a private .
3Rd- can't re -use code in structure but in class we can re-use same code in many time called inhertence

Using base assignment operator to rewrite only part of struct [duplicate]

Assuming I have a base class A and publicly derived class B, how should I assign A object to the A base class subobject of B?
class A {...};
class B : public A {...};
A a(..);
B b(..);
static_cast<A&>(b) = a; ???
Is that doable without writing assignement operator for B? Are there any potential problems with casting b to A&? Is that standard conformant?
Writing another answer to demonstrate why and how assign a base class object to a derived class object.
struct TimeMachineThing_Data {
..
..
};
class TimeMachineThing : private TimeMachineThing_Data
{
static std::stack<TimeMachineThing_Data> m_stateHistory;
void SaveState() {
m_stateHistory.push_back( static_cast<TimeMachineThing_Data&>(*this) );
}
void RestoreState() {
static_cast<TimeMachineThing_Data&>(*this) = m_stateHistory.front();
m_stateHistory.pop_front();
}
};
It's very useful and fully legitimate.
(Here is private inheritance, so only internally TimeMachineThing IS-A TimeMachinetime_Data)
Another one.
struct StructWithHundresField {
string title;
string author;
...
StructWithHundresField() {
...
}
};
class EasyResetClass : public StructWithHundresField {
int not_reset_this_attriute;
public:
void ResetToInitialStateAtAnyTime() {
static_cast<StructWithHundresField&>(*this) = StructWithHundresField();
}
}
That's a really bad idea. A is the base, B is a derived type. By casting B to an A, you are now using A's assignment operator, which isn't going to touch any of the extra derived data. At the end of that assignment, b is still considered to be of type B, even though it now contains an A. This is the opposite of the way inheritance is meant to be used.
Changing the line to b = reinterpret_cast<B&>(a); would be even worse. Then you would be pretending that a is a B when it's not, and you be reading invalid memory.
If you truly want to do this kind of assignment, you want:
class B : public A {
B& operator= (const A& a) { ... }
};
Then you can write a function to copy the information from the A, and somehow deal with the extra information in the derived type B, plus this would allow you to simply write:
b = a;
In C++ (as with other OOP languages) inheritance establish Is-A relationship.
That is, if B publicly inherit A, B = A.
You always can cast B instance to A reference without any worry.
Think for a minute about whether this is a good idea. Remember that if you have B subclassing A, then every B is an A but not every A is a B. For example, every dog is a mammal, but not every mammal is a dog. If you have a concrete B object, trying to set it to an A object isn't mathematically well-defined in most cases. Moreover, in the world of C++, because you B object is statically typed as a B, you can never assign it an object of type A in a way that will make it stop being a B. At best, you're going to overwrite just the A portion of the B object without changing any of the B-specific parts.
Slicing assignment is safe only, if your base class is in
standard layout: https://en.cppreference.com/w/cpp/types/is_standard_layout . Better even, if your derived class is also standard layout.
In particular, your base class must not contain virtual methods or a virtual destructor, and all non-static data members must have the same access control (like public or private). Your base class may have a base class itself, and it may have data members, that are objects of other classes, but all those classes, that you that way inherit into your base class, must also be standard layout.
If your base class is standard layout, then there is nothing wrong with a slicing assignment to it, as that is guaranteed to only touch the data members of the base class. All other cases are unsafe, though.
I would say you need an assignment operator that specifically copies an A object to a B object.
In general, it's a good idea to have one any way when copying objects of the same type. But objects of different types make it even more important.
static_cast<TimeMachineThing_Data&>(*this) = m_stateHistory.front(); can be rewritten without the cast as TimeMachineThing_Data & data = *this; data = m_stateHistory.front();.
Everyone should know assignment is a covariant binary operator and therefore cannot work correctly with virtual functions. This is true for most binary operators, but assignment is special because it is part of the C++ language.
If you are using OO, your objects should be uncopyable and always represented by pointers. Uniqueness of object identity is the heart of OO: objects are not values, they have a unique value (their address).
If you are playing with values you should be using the appropriate concepts: functional programming (FP). That's closures (applicative objects), switches, templates, variants, and other stuff.
Try to get a solid understanding of each before mixing them. In general FP subsumes OO so is the general methodology: OO is a special case that in special circumstances delivers safe dynamic dispatch. OO dispatch is linear which means it handles an unbounded set of subtypes but it also applies only to properties (functions with one variant argument, namely the object) and can't work for anything higher order (functions with more than one variant argument). Assignment is just another 2-ary function, hence, it can't be dispatched with virtual functions.

Why Microsoft uses a struct for directX library instead of a class? [duplicate]

This question was already asked in the context of C#/.Net.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
I'll start with an obvious difference:
If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.
I'm sure there are other differences to be found in the obscure corners of the C++ specification.
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.
Quoting The C++ FAQ,
[7.8] What's the difference between
the keywords struct and class?
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.
It's worth remembering C++'s origins in, and compatibility with, C.
C has structs, it has no concept of encapsulation, so everything is public.
Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.
On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).
So a new keyword, class was introduced to be exactly like a struct, but private by default.
If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.
In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.
Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.
According to Stroustrup in the C++ Programming Language:
Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
Functionally, there is no difference other than the public / private
Members of a class are private by default and members of struct are public by default.
For example program 1 fails in compilation and program 2 works fine.
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error because inheritance is private
getchar();
return 0;
}
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine because inheritance is public
getchar();
return 0;
}
STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)
Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.
In effect, structs are about data, classes are about code.
However, you do need to understand that these are merely abstractions. It's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.
Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
The difference between class and struct is a difference between keywords, not between data types. This two
struct foo : foo_base { int x;};
class bar : bar_base { int x; };
both define a class type. The difference of the keywords in this context is the different default access:
foo::x is public and foo_base is inherited publicly
bar::x is private and bar_base is inherited privately
The members of a structure are public by default, the members of class are private by default.
Default inheritance for Structure from another structure or class is public.Default inheritance for class from another structure or class is private.
class A{
public:
int i;
};
class A2:A{
};
struct A3:A{
};
struct abc{
int i;
};
struct abc2:abc{
};
class abc3:abc{
};
int _tmain(int argc, _TCHAR* argv[])
{
abc2 objabc;
objabc.i = 10;
A3 ob;
ob.i = 10;
//A2 obja; //privately inherited
//obja.i = 10;
//abc3 obss;
//obss.i = 10;
}
This is on VS2005.
Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.
One other thing to note, if you updated a legacy app that had structs to use classes you might run into the following issue:
Old code has structs, code was cleaned up and these changed to classes.
A virtual function or two was then added to the new updated class.
When virtual functions are in classes then internally the compiler will add extra pointer to the class data to point to the functions.
How this would break old legacy code is if in the old code somewhere the struct was cleared using memfill to clear it all to zeros, this would stomp the extra pointer data as well.
Another main difference is when it comes to Templates. As far as I know, you may use a class when you define a template but NOT a struct.
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
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.
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.
You can use template<class T> but not template<struct T>.
Note also that the C++ standard allows you to forward-declare a type as a struct, and then use class when declaring the type and vice-versa. Also, std::is_class<Y>::value is true for Y being a struct and a class, but is false for an enum class.
Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php
So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.
It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.
ISO IEC 14882-2003
9 Classes
§3
A structure is a class defined with
the class-key struct; its members
and base classes (clause 10) are
public by default (clause 11).
The other answers have mentioned the private/public defaults, (but note that a struct is a class is a struct; they are not two different items, just two ways of defining the same item).
What might be interesting to note (particularly since the asker is likely to be using MSVC++ since he mentions "unmanaged" C++) is that Visual C++ complains under certain circumstances if a class is declared with class and then defined with struct (or possibly the other way round), although the standard says that is perfectly legal.
. In classes all the members by default are private but in structure
members are public by default.
There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide.
Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should
typically be used for grouping data.
The class default access type is private, and the default mode for
inheritance is private. A class should be used for grouping data and
methods that operate on that data.
In short, the convention is to use struct when the purpose is to
group data, and use classes when we require data abstraction and,
perhaps inheritance.
In C++ structures and classes are passed by value, unless explicitly
de-referenced. In other languages classes and structures may have
distinct semantics - ie. objects (instances of classes) may be passed
by reference and structures may be passed by value. Note: There are
comments associated with this question. See the discussion page to
add to the conversation.
While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.
This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).
There exists also unwritten rule that tells:
If data members of class have no association with itself, use struct.
If value of data member depends on another value of data member, use class.
f.e
class Time
{
int minutes;
int seconds;
}
struct Sizes
{
int length;
int width;
};
You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .
√ CONSIDER defining a struct instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
X AVOID defining a struct unless the type has all of
the following characteristics:
It logically represents a single value,
similar to primitive types (int, double, etc.).
It has an instance
size under 16 bytes.
It is immutable.
It will not have to be boxed
frequently.
The difference between struct and class keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct or union is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct for data and class for code sake. For more information contact other sources.
Out of all these factors,it can be concluded that concept Class is highly suitable to represent real world objects rather than "Structures".Largely because OOP concepts used in class are highly practical in explaining real world scenarios therefore easier to merge them to reality.For an example,default inheritance is public for structs but if we apply this rule for real world,it's ridiculous.But in a class default inheritance is private which is more realistic.
Anyways,what i need to justify is Class is a much broader,real world applicable concept whereas Structure is a primitive Concept with poor internal organization(Eventhough struct follows OOP concepts,they have a poor meaning)
Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.
When developing large project with tons of people without class, you may finally get complicated coupled code because everybody use whatever functions and data they want. class provides permission controls and inherents to enhance decoupling and reusing codes.
If you read some software engineering principles, you'll find most standards can not be implemented easily without class. for example:
http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
BTW, When a struct allocates a crunch of memory and includes several variables, value type variables indicates that values are embbeded in where struct is allocated. In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.
The main difference between structure and class keyword in oops is that, no public and private member declaration present in structure.and the data member and member function can be defined as public, private as well as protected.
The main difference between struct and class is that in struct you can only declare data variables of different data types while in class you can declare data variables,member functions and thus you can manipulate data variables through functions.
-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it .
while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..
But it depennds on the programmer which way he/she finds suitable...according to me i prefer class everytime just because it supports OOPs and thats the reason it is implemented in almost every languages and its the wonderful feature of all time programming ;-)
And yeah the most unforgotten difference i forgot to mention is that class supports data hiding and also supports operations that are performed on built in data types while struct doesnt !
I found an other difference. if you do not define a constructor in a class, the compiler will define one. but in a struct if you do not define a constructor, the compiler do not define a constructor too. so in some cases that we really do not need a constructor, struct is a better choice (performance tip).
and sorry for my bad English.
Classes are Reference types and Structures are Values types.
When I say Classes are reference types,
basically they will contain the address of an instance variables.
For example:
Class MyClass
{
Public Int DataMember; //By default, accessibility of class data members
//will be private. So I am making it as Public which
//can be accessed outside of the class.
}
In main method,
I can create an instance of this class using new operator that allocates memory for this class
and stores the base address of that into MyClass type variable(_myClassObject2).
Static Public void Main (string[] arg)
{
MyClass _myClassObject1 = new MyClass();
_myClassObject1.DataMember = 10;
MyClass _myClassObject2 = _myClassObject1;
_myClassObject2.DataMember=20;
}
In the above program,
MyClass _myClassObject2 = _myClassObject1;
instruction indicates that both variables of type MyClass
myClassObject1
myClassObject2
and will point to the same memory location.
It basically assigns the same memory location into another variable of same type.
So if any changes that we make in any one of the objects type MyClass will have an effect on another
since both are pointing to the same memory location.
"_myClassObject1.DataMember = 10;" at this line both the object’s data members will contain the value of 10.
"_myClassObject2.DataMember = 20;" at this line both the object’s data member will contains the value of 20.
Eventually, we are accessing datamembers of an object through pointers.
Unlike classes, structures are value types.
For example:
Structure MyStructure
{
Public Int DataMember; //By default, accessibility of Structure data
//members will be private. So I am making it as
//Public which can be accessed out side of the structure.
}
Static Public void Main (string[] arg)
{
MyStructure _myStructObject1 = new MyStructure();
_myStructObject1.DataMember = 10;
MyStructure _myStructObject2 = _myStructObject1;
_myStructObject2.DataMember = 20;
}
In the above program,
instantiating the object of MyStructure type using new operator and
storing address into _myStructObject variable of type MyStructure and
assigning value 10 to data member of the structure using "_myStructObject1.DataMember = 10".
In the next line,
I am declaring another variable _myStructObject2 of type MyStructure and assigning _myStructObject1 into that.
Here .NET C# compiler creates another copy of _myStructureObject1 object and
assigns that memory location into MyStructure variable _myStructObject2.
So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue.
That’s why we are saying Structures are value types.
So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.
Classes will support an Inheritance whereas Structures won’t.
How are we saying that?
And what is the reason behind that?
The answer is Classes.
It can be abstract, sealed, static, and partial and can’t be Private, Protected and protected internal.
There are 3 basic difference between structure and class
1St- memory are reserved for structure in stack memory (which is near to programming language )whether for class in stack memory are reserved for only reffrence and actual memory are reserved in heap memory.
2Nd - By default structure treat as a public whether class treat as a private .
3Rd- can't re -use code in structure but in class we can re-use same code in many time called inhertence

Do struct have better performance over classes in embeded system [duplicate]

This question was already asked in the context of C#/.Net.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
I'll start with an obvious difference:
If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.
I'm sure there are other differences to be found in the obscure corners of the C++ specification.
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.
Quoting The C++ FAQ,
[7.8] What's the difference between
the keywords struct and class?
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.
It's worth remembering C++'s origins in, and compatibility with, C.
C has structs, it has no concept of encapsulation, so everything is public.
Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.
On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).
So a new keyword, class was introduced to be exactly like a struct, but private by default.
If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.
In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.
Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.
According to Stroustrup in the C++ Programming Language:
Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
Functionally, there is no difference other than the public / private
Members of a class are private by default and members of struct are public by default.
For example program 1 fails in compilation and program 2 works fine.
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error because inheritance is private
getchar();
return 0;
}
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine because inheritance is public
getchar();
return 0;
}
STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)
Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.
In effect, structs are about data, classes are about code.
However, you do need to understand that these are merely abstractions. It's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.
Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
The difference between class and struct is a difference between keywords, not between data types. This two
struct foo : foo_base { int x;};
class bar : bar_base { int x; };
both define a class type. The difference of the keywords in this context is the different default access:
foo::x is public and foo_base is inherited publicly
bar::x is private and bar_base is inherited privately
The members of a structure are public by default, the members of class are private by default.
Default inheritance for Structure from another structure or class is public.Default inheritance for class from another structure or class is private.
class A{
public:
int i;
};
class A2:A{
};
struct A3:A{
};
struct abc{
int i;
};
struct abc2:abc{
};
class abc3:abc{
};
int _tmain(int argc, _TCHAR* argv[])
{
abc2 objabc;
objabc.i = 10;
A3 ob;
ob.i = 10;
//A2 obja; //privately inherited
//obja.i = 10;
//abc3 obss;
//obss.i = 10;
}
This is on VS2005.
Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.
One other thing to note, if you updated a legacy app that had structs to use classes you might run into the following issue:
Old code has structs, code was cleaned up and these changed to classes.
A virtual function or two was then added to the new updated class.
When virtual functions are in classes then internally the compiler will add extra pointer to the class data to point to the functions.
How this would break old legacy code is if in the old code somewhere the struct was cleared using memfill to clear it all to zeros, this would stomp the extra pointer data as well.
Another main difference is when it comes to Templates. As far as I know, you may use a class when you define a template but NOT a struct.
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
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.
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.
You can use template<class T> but not template<struct T>.
Note also that the C++ standard allows you to forward-declare a type as a struct, and then use class when declaring the type and vice-versa. Also, std::is_class<Y>::value is true for Y being a struct and a class, but is false for an enum class.
Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php
So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.
It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.
ISO IEC 14882-2003
9 Classes
§3
A structure is a class defined with
the class-key struct; its members
and base classes (clause 10) are
public by default (clause 11).
The other answers have mentioned the private/public defaults, (but note that a struct is a class is a struct; they are not two different items, just two ways of defining the same item).
What might be interesting to note (particularly since the asker is likely to be using MSVC++ since he mentions "unmanaged" C++) is that Visual C++ complains under certain circumstances if a class is declared with class and then defined with struct (or possibly the other way round), although the standard says that is perfectly legal.
. In classes all the members by default are private but in structure
members are public by default.
There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide.
Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should
typically be used for grouping data.
The class default access type is private, and the default mode for
inheritance is private. A class should be used for grouping data and
methods that operate on that data.
In short, the convention is to use struct when the purpose is to
group data, and use classes when we require data abstraction and,
perhaps inheritance.
In C++ structures and classes are passed by value, unless explicitly
de-referenced. In other languages classes and structures may have
distinct semantics - ie. objects (instances of classes) may be passed
by reference and structures may be passed by value. Note: There are
comments associated with this question. See the discussion page to
add to the conversation.
While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.
This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).
There exists also unwritten rule that tells:
If data members of class have no association with itself, use struct.
If value of data member depends on another value of data member, use class.
f.e
class Time
{
int minutes;
int seconds;
}
struct Sizes
{
int length;
int width;
};
You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .
√ CONSIDER defining a struct instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
X AVOID defining a struct unless the type has all of
the following characteristics:
It logically represents a single value,
similar to primitive types (int, double, etc.).
It has an instance
size under 16 bytes.
It is immutable.
It will not have to be boxed
frequently.
The difference between struct and class keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct or union is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct for data and class for code sake. For more information contact other sources.
Out of all these factors,it can be concluded that concept Class is highly suitable to represent real world objects rather than "Structures".Largely because OOP concepts used in class are highly practical in explaining real world scenarios therefore easier to merge them to reality.For an example,default inheritance is public for structs but if we apply this rule for real world,it's ridiculous.But in a class default inheritance is private which is more realistic.
Anyways,what i need to justify is Class is a much broader,real world applicable concept whereas Structure is a primitive Concept with poor internal organization(Eventhough struct follows OOP concepts,they have a poor meaning)
Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.
When developing large project with tons of people without class, you may finally get complicated coupled code because everybody use whatever functions and data they want. class provides permission controls and inherents to enhance decoupling and reusing codes.
If you read some software engineering principles, you'll find most standards can not be implemented easily without class. for example:
http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
BTW, When a struct allocates a crunch of memory and includes several variables, value type variables indicates that values are embbeded in where struct is allocated. In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.
The main difference between structure and class keyword in oops is that, no public and private member declaration present in structure.and the data member and member function can be defined as public, private as well as protected.
The main difference between struct and class is that in struct you can only declare data variables of different data types while in class you can declare data variables,member functions and thus you can manipulate data variables through functions.
-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it .
while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..
But it depennds on the programmer which way he/she finds suitable...according to me i prefer class everytime just because it supports OOPs and thats the reason it is implemented in almost every languages and its the wonderful feature of all time programming ;-)
And yeah the most unforgotten difference i forgot to mention is that class supports data hiding and also supports operations that are performed on built in data types while struct doesnt !
I found an other difference. if you do not define a constructor in a class, the compiler will define one. but in a struct if you do not define a constructor, the compiler do not define a constructor too. so in some cases that we really do not need a constructor, struct is a better choice (performance tip).
and sorry for my bad English.
Classes are Reference types and Structures are Values types.
When I say Classes are reference types,
basically they will contain the address of an instance variables.
For example:
Class MyClass
{
Public Int DataMember; //By default, accessibility of class data members
//will be private. So I am making it as Public which
//can be accessed outside of the class.
}
In main method,
I can create an instance of this class using new operator that allocates memory for this class
and stores the base address of that into MyClass type variable(_myClassObject2).
Static Public void Main (string[] arg)
{
MyClass _myClassObject1 = new MyClass();
_myClassObject1.DataMember = 10;
MyClass _myClassObject2 = _myClassObject1;
_myClassObject2.DataMember=20;
}
In the above program,
MyClass _myClassObject2 = _myClassObject1;
instruction indicates that both variables of type MyClass
myClassObject1
myClassObject2
and will point to the same memory location.
It basically assigns the same memory location into another variable of same type.
So if any changes that we make in any one of the objects type MyClass will have an effect on another
since both are pointing to the same memory location.
"_myClassObject1.DataMember = 10;" at this line both the object’s data members will contain the value of 10.
"_myClassObject2.DataMember = 20;" at this line both the object’s data member will contains the value of 20.
Eventually, we are accessing datamembers of an object through pointers.
Unlike classes, structures are value types.
For example:
Structure MyStructure
{
Public Int DataMember; //By default, accessibility of Structure data
//members will be private. So I am making it as
//Public which can be accessed out side of the structure.
}
Static Public void Main (string[] arg)
{
MyStructure _myStructObject1 = new MyStructure();
_myStructObject1.DataMember = 10;
MyStructure _myStructObject2 = _myStructObject1;
_myStructObject2.DataMember = 20;
}
In the above program,
instantiating the object of MyStructure type using new operator and
storing address into _myStructObject variable of type MyStructure and
assigning value 10 to data member of the structure using "_myStructObject1.DataMember = 10".
In the next line,
I am declaring another variable _myStructObject2 of type MyStructure and assigning _myStructObject1 into that.
Here .NET C# compiler creates another copy of _myStructureObject1 object and
assigns that memory location into MyStructure variable _myStructObject2.
So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue.
That’s why we are saying Structures are value types.
So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.
Classes will support an Inheritance whereas Structures won’t.
How are we saying that?
And what is the reason behind that?
The answer is Classes.
It can be abstract, sealed, static, and partial and can’t be Private, Protected and protected internal.
There are 3 basic difference between structure and class
1St- memory are reserved for structure in stack memory (which is near to programming language )whether for class in stack memory are reserved for only reffrence and actual memory are reserved in heap memory.
2Nd - By default structure treat as a public whether class treat as a private .
3Rd- can't re -use code in structure but in class we can re-use same code in many time called inhertence

How is C++'s multiple inheritance implemented?

Single inheritance is easy to implement. For example, in C, the inheritance can be simulated as:
struct Base { int a; }
struct Descendant { Base parent; int b; }
But with multiple inheritance, the compiler has to arrange multiple parents inside newly constructed class. How is it done?
The problem I see arising is: should the parents be arranged in AB or BA, or maybe even other way? And then, if I do a cast:
SecondBase * base = (SecondBase *) &object_with_base1_and_base2_parents;
The compiler must consider whether to alter or not the original pointer. Similar tricky things are required with virtuals.
The following paper from the creator of C++ describes a possible implementation of multiple inheritance:
Multiple Inheritance for C++ - Bjarne Stroustrup
There was this pretty old MSDN article on how it was implemented in VC++.
And then, if I do a cast:
SecondBase base = (SecondBase *) object_with_base1_and_base2_parents;
The compiler must consider whether to alter or not the original pointer. Similar tricky things with virtuals.
With non-virutal inheritance this is less tricky than you might think - at the point where the cast is compiled, the compiler knows the exact layout of the derived class (after all, the compiler did the layout). Usually all that happens is a fixed offset (which may be zero for one of the base classes) is added/subtracted from the derived class pointer.
With virutal inheritance it is maybe a bit more complex - it may involve grabbing an offset from a vtbl (or similar).
Stan Lippman's book, "Inside the C++ Object Model" has very good descriptions of how this stuff might (and often actually does) work.
Parents are arranged in the order that they're specified:
class Derived : A, B {} // A comes first, then B
class Derived : B, A {} // B comes first, then A
Your second case is handled in a compiler-specific manner. One common method is using pointers that are larger than the platform's pointer size, to store extra data.
This is an interesting issue that really isn't C++ specific. Things get more complex also when you have a language with multiple dispatch as well as multiple inheritance (e.g. CLOS).
People have already noted that there are different ways to approach the problem. You might find reading a bit about Meta-Object Protocols (MOPs) interesting in this context...
Its entirely down to the compiler how it is done, but I beleive its generally done througha heirarchical structure of vtables.
I have performed simple experiment:
class BaseA { int a; };
class BaseB { int b; };
class Descendant : public BaseA, BaseB {};
int main() {
Descendant d;
BaseB * b = (BaseB*) &d;
Descendant *d2 = (Descendant *) b;
printf("Descendant: %p, casted BaseB: %p, casted back Descendant: %p\n", &d, b, d2);
}
Output is:
Descendant: 0xbfc0e3e0, casted BaseB: 0xbfc0e3e4, casted back Descendant: 0xbfc0e3e0
It's good to realise that static casting does not always mean "change the type without touching the content". (Well, when data types do not fit each other, then there will be also an interference into content, but it's different situation IMO).