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.

40 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

Leave a Reply