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.

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

  1. Sunil Says:

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

  2. saima ahmad Says:

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

  3. jeanyna Says:

    Nice article man. Keep up the good work.

  4. gurvinder Says:

    class defined by class keword
    but struture defined by struct keword

  5. anand Says:

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

  6. ruchA Says:

    Can c++ structures use the polymorphism concept ?

  7. Keshav Says:

    Hi sunil, can you explain the concept of padding.

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

  9. Léo Says:

    @Sunil: Are you sure about padding?

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

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

  12. shri "the final comment" amin Says:

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

  13. Dhiraj Says:

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

  14. NeoCambell Says:

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

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

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

  17. saikat Says:

    same answer as bin says

  18. Suminda Says:

    You are all (in)correct ;D

  19. Suminda Says:

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

  20. 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;
    }

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

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

  23. Iliana Carr Says:

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

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

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

  26. vips Says:

    class access specifier (private public protected)

  27. vips Says:

    class= structure+function

  28. varsha patil Says:

    In the struct we can not* declare a function but in the class we can declare function …..

Leave a Reply