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.

77 Responses to “Differences between C++ Classes and Structs”

  1. ariock Says:

    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]}; )

  2. Steve Says:

    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.

  3. pqnelson Says:

    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?

  4. Srikanth Says:

    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++.

  5. Mahesh Says:

    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.

  6. Pete Says:

    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.

  7. PHASUDI MOKOBANE Says:

    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

  8. Rupert Says:

    in C++ between a struct and object (class) of same size and with same members, which is faster to run?

  9. baskar Says:

    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

  10. qwerty Says:

    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.

  11. Waqas Rasheed Says:

    Sir, Please send me technical differences between classes and structures
    using c++.net

  12. Manigandan Says:

    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’

  13. Manigandan Says:

    Sorry. I found it. class D declaring has to come after class B.

  14. vijayendra Says:

    i didnt satisfied wiith the answer given…
    it should be more technical.there isnt any difference on case of memory..

  15. gaurav Says:

    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

  16. Bin Says:

    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?

  17. Gregory Kramida Says:

    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.

  18. Gregory Kramida Says:

    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

  19. Sadanand Teggi Says:

    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 …

  20. Frans Says:

    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.

  21. kiran kuar.y Says:

    yes

  22. kiran kuar.y Says:

    yes. c++ classes have constructors,where as structs not…

    c++ suppots for dynamic hidding

  23. tanuja naik Says:

    how is struct is userdefined type ? explain please?

  24. tanuja naik Says:

    how struct is userdefined datatype?please explain?

  25. Adrien Says:

    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.

  26. kk Says:

    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 .

  27. rjt Says:

    structure can be an object of a class, but cannot be the other way round

  28. abzal Says:

    please anyone can explain me about the differences between classes and structure in a short notes…..?

  29. fjs Says:

    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.

  30. fjs Says:

    oops, i meant a class can be an object of a STRUCT

  31. Iram Says:

    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?

  32. MG Says:

    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.

  33. Samir Says:

    Very clear answer. thanks MG. No more questions…

  34. ghar dash Says:

    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

  35. Rizwan Says:

    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 . . . . .

  36. tahir Says:

    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

  37. Rizwan Says:

    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

  38. atif Says:

    the difference b\w struct n class is that struct starts with s n class starts with c….. :)

  39. karan kapoor Says:

    the major difference btw structure and class is dat structure follow top down approach while class follow bootom up approach

  40. Raj Kumar Arora Says:

    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

  41. abi Says:

    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

  42. Yiannis Says:

    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.

  43. Suryamaruti Says:

    I am satisfied with your answer.tnq

  44. Girish Says:

    There is no particular difference between structure and class. It is retained to ensure compatibility with C

  45. Girish pillai Says:

    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.

  46. Kundan Says:

    I think no one knows wny classes and structure both are present when there is no difference except in private / public thing!!!

  47. PISG Says:

    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

  48. Rob Says:

    Unbelievable how many people are posting their Bullshit here without even bothering to read…

  49. Vinit M Says:

    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.

  50. Sunil Says:

    There would be padding in case of structures, but no padding in case of classes.

  51. Sunil Says:

    There would be padding in structures, but there is no padding in classes.

  52. saima ahmad Says:

    plz tell me about the protected(acces specfier) with example

  53. jeanyna Says:

    Nice article man. Keep up the good work.

  54. gurvinder Says:

    class defined by class keword
    but struture defined by struct keword

  55. anand Says:

    please stop commenting bull shit and try to post you have answer people’s query correctly…..

  56. ruchA Says:

    Can c++ structures use the polymorphism concept ?

  57. Keshav Says:

    Hi sunil, can you explain the concept of padding.

  58. Nandhini Says:

    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…

  59. Léo Says:

    @Sunil: Are you sure about padding?

  60. harshita Says:

    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.

  61. Jadhav Harshawardhan Says:

    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

  62. shri "the final comment" amin Says:

    this is the last comment regarding this matter. people suck, especially computer geeks and programming gods.

  63. Dhiraj Says:

    i am asking you the correct answer. and instead of it you are providing me silly comments. hoples

  64. NeoCambell Says:

    Another nice explanation to the same problem can be found at http://www.expertcore.org/viewtopic.php?f=8&p=9281

  65. Bill H. Says:

    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.

  66. Bill H. Says:

    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.

  67. saikat Says:

    same answer as bin says

  68. Suminda Says:

    You are all (in)correct ;D

  69. Suminda Says:

    idiots…Main difference is a class is defined with ‘class’ keyword and a struct is defined with ‘struct’ keyword

  70. Aijaz Says:

    class A
    {
    public:
    int a;
    };

    struct B : A { };

    struct C
    {
    int c;
    } ————-> U forgot a semicolon here,
    struct or class inheritance is not a problem.

    class D : C { };

    int main()
    {
    B b;
    D d;
    b.a = 1;
    d.c = 2;
    }

  71. Anonymous Says:

    class A
    {
    public:
    int a;
    };

    struct B : A { };

    struct C
    {
    int c;
    }; —————————-> Note semicolon here.

    class D : public C { }; —–> Note public here.

    int main()
    {
    B b;
    D d;
    b.a = 1;
    d.c = 2;
    }

    The above one perfectly works fine for me on gcc – linux.

  72. Sap Says:

    Differences between classes and structs:-

    Although classes and structures are similar in both the way they are declared and how they are used, there are some significant differences. Classes are reference types and structs value types. A structure is allocated on the stack when it is declared and the variable is bound to its address. It directly contains the value. Classes are different because the memory is allocated as objects on the heap. Variables are rather managed pointers on the stack which point to the objects. They are references.

    Structures require some more than classes. For example, you need to explicitly create a default constructor which takes no arguments to initialize the struct and its members. The compiler will create a default one for classes. All fields and properties of a struct must have been initialized before an instance is created. Structs do not have finalizers and cannot inherit from another class like classes do. However, they inherit from System.ValueType, that inherits from System.Object. Structs are more suitable for smaller constructs of data.

  73. Iliana Carr Says:

    what are three ways that classes can relate to each other??

  74. YuriOh Says:

    @Sap: This is true for C# but not for C++
    In C++ there is no “Reference” or “Value Type”. Your text belongs to C#.

  75. Neetu Says:

    I think there is only the difference is the member of a class are private by default and member of a structure are public by default. Also in a structure struct keyword is used and in a class the keyword class is used.

  76. vips Says:

    class access specifier (private public protected)

  77. vips Says:

    class= structure+function

Leave a Reply