Differences between C++ Classes and Structs
Probably the most frequently asked interview question that I have received is one that explores the difference between C++ classes and structs. Such a question was asked by a Northrop Grumman recruiter during a career fair at UC Irvine. I was also asked this sort of question during an on-site interview at Heavy Iron Studios. Recently, it has been asked during a phone interview with Amazon.com.
My answer typically states that members of a class are private by default, whereas members of a struct are public by default. Inheritance between classes is also private by default, and inheritance between structs is public by default. The interviewer was usually satisfied with this answer, which Dr. Raymond Klefstad fed to my first computer science class. Lately, I was interested in the nontrivial cases that bring me uncertainty: a struct inheriting from a class and a class inheriting from a struct.
Code to test the behavior for these cases is presented below:
class A
{
public:
int a;
};
struct B : A { };
struct C
{
int c;
}
class D : C { };
int main()
{
B b;
D d;
b.a = 1;
d.c = 2;
}
Although a recent version of the GNU project C++ compiler treats the assignment of 2 into d.c in the above example as a compile-time error, a programmer who is more interested in standards compliance should refer to the C++ standard. After all, compilers do not determine standard behavior; standards prescribe standard behavior for compilers. The GNU project C++ compiler is consistent with 11.2.2 of ISO/IEC 14882-2003, which states that the kind of inheritance is determined by the derived class being declared as a class or struct when an access specificer for the base class is absent. The standard also clarifies the second part of the answer to the above interview question.
April 6th, 2007 at 6:16 am
Hi, in terms of language this satisfy my well, however in terms of memory bytes, is there or not a difference between a struct and a class?
what if I use a write() call passing a pointer to a struct, or if I pass a pointer to a class?
What if my class has virtual inheritance?
(Suppose I want to send my class over the network, and it contains no dynamic pointer ie: class a { int a,b,c; long d; char e[25]}; )
April 9th, 2007 at 1:07 am
There isn’t a difference in memory used between C++ structs and classes. Using write() on a C++ struct has the same effect as using write() on a C++ class. Structs can use virtual inheritance as well.
I really do not recommend sending objects with, I assume, write(). Serializing objects into components that allow the desired objects and their relationships to other objects to be reconstructed at the other side of the network connection is a preferred method.
June 6th, 2007 at 4:57 pm
Interesting, but if I may ask, how exactly does C++ struct inheritance work? I mean, if we were to use some generic code, like
struct A {
int x;
}
struct B : A {
int y;
}
How would the corresponding code appear in C? How does this C++ version look in memory compared to how the C version appears in memory?
June 7th, 2007 at 1:20 am
class D : C { };
this code has the class inheriting from a struct, in private access, since the default access specifier is private for classes. This code compiles well for unix CC complier, also no probs with vc++.
June 21st, 2007 at 11:51 pm
Structures Are Diffrent from Class in various ways :-
1. Structures didnot support data hiding, but classes can.
2. Priovate functions totally hidden in classes.
3. There is also differnce in memory allocation.
December 11th, 2007 at 10:39 am
Mahesh, that is wrong.
All 3 of your points are wrong when considering structs in C++.
It sounds like you are comparing C structs with C++ classes.
But in C++ struct’s and classes both support private member data, private member functions, and have no difference in memory allocation.
Try it if you don’t believe it. Or just look it up in the spec.
March 13th, 2008 at 10:16 am
IN C++ THE TECHNICAL DIFFERENCE BETWEEN CLASSES AND STRUCT IS THAT WITHOUT THE USE OF RESERVED WORD PUBLIC AND PRIVATE, MEMBER FUNCTION ARE PRIVATE BY CLASS AND PUBLIC BY STRUCT
April 2nd, 2008 at 6:16 am
in C++ between a struct and object (class) of same size and with same members, which is faster to run?
June 1st, 2008 at 11:54 am
what are uses of class in c++.because in structure do all work like class.so what is need of class.please tell the resion
August 14th, 2008 at 2:51 pm
Rupert: what do you mean by “which is faster to run?” Instances of classes and structs are all “objects.” Furthermore, as has been stated multiple times in this post, the only difference is the default visibility of members.
class C {
public:
int pub;
private:
int priv;
};
is identical in every respect (except the default behavior when they are inherited) to
struct S {
public:
int pub;
private:
int priv;
};
If you have a pointer ‘s’ to an object of type S and a pointer ‘c’ to an object of type C then “s->pub = 0;” and “c->pub = 0;” then not only is the behavior identical, but the generated assembly is identical.
August 24th, 2008 at 10:43 am
Sir, Please send me technical differences between classes and structures
using c++.net
September 10th, 2008 at 9:33 pm
struct A
{
int x;
};
struct C : A {};
class D : public B{};
class B
{
public :
int y;
};
int main()
{
A a;
B b;
a.x = 10;
b.y = 20;
C c;
D d;
c.x = 40;
d.y =50;
}
What’s wrong in this code?
I am getting the following error.
#g++ struct.cpp
struct.cpp:7: error: expected class-name before ‘{‘ token
struct.cpp: In function `int main()’:
struct.cpp:24: error: ‘class D’ has no member named ‘y’
September 10th, 2008 at 9:35 pm
Sorry. I found it. class D declaring has to come after class B.
November 7th, 2008 at 9:28 am
i didnt satisfied wiith the answer given…
it should be more technical.there isnt any difference on case of memory..
November 13th, 2008 at 11:46 am
what is the difference between a C++ structure and a class?
What comes to my mind are
1) structures in c++ doesnot provide datahiding where as a class provides datahiding
2)classes support polymorphism, whereas structures donot
December 21st, 2008 at 9:01 pm
Can you show me more why structures do not supoort data hiding? I was told it can also have functions, just because all the data are public. And also why structures can not support polymorphism? No virtual function?
January 2nd, 2009 at 9:14 am
It is the general convention to treat objects (of a certain class) as pointers, and in truth, every object is a pointer.
1. A struct may not have constructors, even if they can have initialization functions. A class of objects has constructors, which you use to create objects.
2. Every object is, in reality, a pointer. This is why the assignment operator that you overload for a class returns a reference to your object (ClassName&) rather than the entire thing (ClassName). Thus, since you can do “SomeClass a = SomeClass(foo);”, it is obvious that a is right away a declared pointer.
January 2nd, 2009 at 9:31 am
The physical differences between C++ structs and classes are minimal, but C structs, however, have much less to them… which is what gaurav was talking about.
Here is a link where the topic is explored deeply and analysis results are clearly stated:
http://carcino.gen.nz/tech/cpp/struct_vs_class.php
January 23rd, 2009 at 2:12 am
Finally you did’t specified that, even C++ struct and C++ classes are almost same, except default behavior of data members, then when should i use struct and when should i use class?? I can use only struct then why classes??
Please give me relevant details …
February 11th, 2009 at 12:50 pm
What it really comes down to is coding standards if your company has any, and readabilty. Most C++ people that are use to seeing classes instead of structs.
Other than that they can both serve as the same identical object. Both can do pure virtual functions/inheritance/ and anything else you have used a class for.
March 7th, 2009 at 7:08 am
yes
March 7th, 2009 at 7:10 am
yes. c++ classes have constructors,where as structs not…
c++ suppots for dynamic hidding
March 8th, 2009 at 3:11 am
how is struct is userdefined type ? explain please?
March 8th, 2009 at 3:12 am
how struct is userdefined datatype?please explain?
April 15th, 2009 at 12:11 am
structs do have constructors.
You can certainly have
struct A
{
A(LPCSTR s) :
m_S(s)
{}
string s;
};
don’t mix the difference between structs in C and structs in C++. Structs in C have no inheritance etc because C doesn’t have it. But C++ does.
April 29th, 2009 at 2:45 am
What do you mean by userdefined ??
Inbuilt data types are like int , char , float , double etc
If we want a datatype which can store a combination of int and a char together,like Age(int) and Name(char) , what will you do ??
You have to make a make your own datatype i.e user-defined datatype ,
which can hold both int and char , that facility is provided by structures and classes .
July 26th, 2009 at 7:09 am
structure can be an object of a class, but cannot be the other way round
August 12th, 2009 at 1:47 am
please anyone can explain me about the differences between classes and structure in a short notes…..?
August 15th, 2009 at 10:46 am
a class can be an object of a class, try it out – it works.
in c++ they are identical apart from the public-private thing.
August 15th, 2009 at 10:46 am
oops, i meant a class can be an object of a STRUCT
October 27th, 2009 at 3:46 am
Is there any difference in allocation of the memory to classes and structures?
Is it true that classes allocate on the stack but structure on the heap?
November 3rd, 2009 at 1:21 pm
The only difference is the default visibility of members (both support data and functions and constructors and destructors).
- classes have private members by default
- structs have public members by default
Either type of object can be created on the stack (transient automatic variable) or on the heap (allocated via the “new” operator and expressly deleted using the “delete” operator). There is no difference in the way the class or struct lays out in memory.
I personally consider it bad form to use default visibility so I don’t do that. So in my case case there is no difference at all.
Some programmers use struct to indicate that the object is simple data. They will add constructors, accessors, assignment operators etcetera for protection. They will also add serialization an deserialization functions if the data is displayed or written to a file.
The same programmers will always use class when the object does something other than just hold data. For example, a class may represent a screen object or an external device, or a database access object. In these cases, the data is at least partly a configuration of the object.
In short, the struct keyword is superfluous and leads to confusion. There is no C++ language-specific reason to use it. It was probably retained to ensure compatibility with older C code.
November 25th, 2009 at 10:32 am
Very clear answer. thanks MG. No more questions…
January 12th, 2010 at 10:08 am
Steve,
Your code compiles using VIsual C++ express 2008. Compiler only compain is about :
‘C::c’ not accessible because ‘D’ uses ‘private’ to inherit from ‘C’
where you have :
class D : C
which can be resolved by making the inheritance public – i.e.
class D : public C {}
- Ghar
February 12th, 2010 at 10:31 am
to me yet the only difference between the strut and class of c++ is that all the members whether they are methods or they are data is that they are public by default in the structures and are private by default private in the case of classes . . . . .
February 12th, 2010 at 11:26 am
in c++ you can do data hiding and inheritance in c++ structures as you do in c++ classes the only differences will be that the if you don’t provide specifier then by default the inheritances of structures is public and of classes is private but you can change it yourself by specifying the specifier you want (public or private ) on the basis of your requirements
February 12th, 2010 at 11:30 am
the differences in structures and classes of c++ is that the membors of structures in c++ are public by default and of classes are private by default ……….. you can do data hiding and inheritance in c++ structures as you do in c++ classes the only differences will be that the if you don’t provide specifier then by default the inheritances of structures is public and of classes is private but you can change it yourself by specifying the specifier you want (public or private ) on the basis of your requirements
March 2nd, 2010 at 11:46 pm
the difference b\w struct n class is that struct starts with s n class starts with c….. :)
June 12th, 2010 at 6:51 am
the major difference btw structure and class is dat structure follow top down approach while class follow bootom up approach
June 12th, 2010 at 9:09 am
Nobody has replied to the question of baskar
———————-
Ref:-
baskar Says:
June 1st, 2008 at 11:54 am
———————-
I am keen to get his answer. When structs are capable of doing all things as classes and have an option of providing access private then why Classes are introduced?
Moreover as I know various class objects has a separate copy of member variables but shares member functions. But various struct objects has a separate copy of everything including member functions. So then how can be structs and classes same on memory usage point of view?
Correct me if I am on wrong track.
Raj Kumar Arora
Er_RajArora@yahoo.com
August 13th, 2010 at 2:57 am
Difference between class and structure in c++:
S.NO ASPECTS CLASS STRUCTURE
1. DEFINITION A collection of similiar A collection of issimiliar
object-types. data-types.
2. KEYWORD CLASS STRUCT
3. ACCES PRIVATE PUBLIC
SPECIFIERS
4. TYPE REFERENCE type VALUE type
5. STORAGE HEAP STACK
CONCEPT
6. PURPOSE Grouping datum,use Grouping datum
inheritance &
poly-morphism
August 27th, 2010 at 5:46 am
What this thread proves is that most developers (well people in general, but it’s of more consequence in the case of developers) don’t pay attention. They think they’re too smart probably.
Hence many replied thinking about C structs, whereas the title clearly states C++ structs. Quite annoying if you ask me.
September 22nd, 2010 at 8:49 am
I am satisfied with your answer.tnq
September 22nd, 2010 at 10:10 pm
There is no particular difference between structure and class. It is retained to ensure compatibility with C
September 22nd, 2010 at 10:58 pm
Difference between class and structure is that-
1. Default data members of class are private and data members of structure are public.
2. A structure cannot be inherted by a class where as a class can be inherited by a structure.
September 28th, 2010 at 5:37 am
I think no one knows wny classes and structure both are present when there is no difference except in private / public thing!!!
November 5th, 2010 at 11:52 pm
There is a difference between struct and class
class stored in heap and its reference type while on other ahnd struct store in stack due to its value type nature
January 3rd, 2011 at 8:10 am
Unbelievable how many people are posting their Bullshit here without even bothering to read…
January 21st, 2011 at 3:50 am
There is no difference in struct and class in C++.
Only difference encounter when we use defualt specifier.
i.e class has Private while struct has Public.
February 1st, 2011 at 3:40 am
There would be padding in case of structures, but no padding in case of classes.
February 1st, 2011 at 3:44 am
There would be padding in structures, but there is no padding in classes.
February 28th, 2011 at 9:57 am
plz tell me about the protected(acces specfier) with example
March 29th, 2011 at 9:25 am
Nice article man. Keep up the good work.
April 27th, 2011 at 8:13 am
class defined by class keword
but struture defined by struct keword
May 19th, 2011 at 4:05 am
please stop commenting bull shit and try to post you have answer people’s query correctly…..
June 21st, 2011 at 7:14 am
Can c++ structures use the polymorphism concept ?
July 8th, 2011 at 1:04 am
Hi sunil, can you explain the concept of padding.
July 13th, 2011 at 8:09 am
Can anyone pls temme if a main function is user defined or built-in type?? It was asked by my HOD mam. And am supposed to give her the correct answer. so pls anyone help me…..do post ur replies as soon as possible…
July 20th, 2011 at 11:23 am
@Sunil: Are you sure about padding?
August 8th, 2011 at 4:12 am
other than all d bullshits posted, this somehow convinced me n helped m ein finding d ans. as dis is a very common ques wrt d interviews, n lets c if dat helps me or not.
September 9th, 2011 at 5:35 am
Their are only three diffrance between struture and class is ,
1) default accsss specifierin class i.e private for class and public for struture
2) keyword class for class and struct for struture
3) Inheritance between classes is also private by default, and inheritance between structs is public by default
September 10th, 2011 at 7:59 pm
this is the last comment regarding this matter. people suck, especially computer geeks and programming gods.
December 8th, 2011 at 10:03 am
i am asking you the correct answer. and instead of it you are providing me silly comments. hoples
January 21st, 2012 at 7:53 pm
Another nice explanation to the same problem can be found at http://www.expertcore.org/viewtopic.php?f=8&p=9281
January 30th, 2012 at 1:00 pm
There is a significant difference between a class and a structure that has not been mentioned beyond the default access level.
The C++ language specification allows compiler writers to add abitrary internal data to a class instance, and this data can be either before or after the regular class data in memory. Some compilers do this. Almost all compilers do this if Run Time Type Information (RTTI) is enabled at compiler time.
More importantly, any future compiler can increase the size of class instances in any future compiler without violating the language specification.
The C++ language specification prohibits adding any data to a structure that contains only non-virtual members. A pointer to a vtable will be added if the struct contains virtual members.
A structure with ‘no’ virtual members is guaranteed to be the size of it’s data elements plus an padding bytes necessary to aligh data members for the current memory alignment.
Thus, unlike a class, the address of a structure with no virtual members is guaranteed to be the same as the address of the first data element in the structure. As mentioned earlier by MG, the struct exists in C++ to allow compatibility with C code.
However, a struct can be occasionally preferable in C++ code. AI a C++ container class with thousands of instances, as adding padding data ‘can’ greatly increase memory utilization. This is because some memory allocators, in order to reduce memory fragmentation, only allocate sizes that are powers of two up to some maximum power of two. Thus, adding a single byte to a size that is already a small power of two can double memory utilization.
January 30th, 2012 at 1:04 pm
By the way, just to clarify my last post and to correct one point above, padding of data members for memory alignment will generally be done in both classes and structs. The difference is that a struct will have no memory added by the compilers beyond the regular alignment padding, and that alignment padding is also used in C, as well as C++.
Depending on compiler switches and/or certain pragma definitions, padding for alignment can be modified or disabled.