What are the differences between struct and class in C++?



13 Answers

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.

Question

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.




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.




  1. The members of a structure are public by default, the members of class are private by default.
  2. 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.




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




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




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.




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




Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.




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.




1) 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;
}
Run on IDE
// 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;
}

2) 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 equilalent to class Derived : private Base {}

int main()
{
  Derived d;
  d.x = 20; // compiler error becuase inheritance is private
  getchar();
  return 0;
}
Run on IDE
// Program 4
#include <stdio.h>

class Base {
public:
    int x;
};

struct Derived : Base { }; // is equilalent to struct Derived : public Base {}

int main()
{
  Derived d;
  d.x = 20; // works fine becuase inheritance is public
  getchar();
  return 0;
}



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)




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.




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




Related