简体   繁体   中英

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

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.

You forget the tricky 2nd difference between classes and structs.

Members of a class defined with the keywords struct<\/em> or union<\/em> are public<\/em> by default.

It's worth remembering C++'s origins in, and compatibility with, C.

C has structs, it has no concept of encapsulation, so everything is public.

Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.

On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).

So a new keyword, class was introduced to be exactly like a struct, but private by default.

If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.

In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.

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

"

According to Stroustrup in the C++ Programming Language :

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

Functionally, there is no difference other than the public / private

  1. Members of a class are private by default<\/strong> and members of struct are public by default<\/strong> .<\/li><\/ol>

    For example program 1 fails in compilation and program 2 works fine.

     And when deriving a class, default access specifier is private<\/strong> .<\/li><\/ol>

    For example program 3 fails in compilation and program 4 works fine.

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

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.

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.

Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). eg 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 difference between class<\/code> and struct<\/code> is a difference between keywords, not between data types. This two

struct foo : foo_base { int x;};
class bar : bar_base { int x; };
  1. The members of a structure are public by default, the members of class are private by default.<\/li>
  2. <\/li><\/ol>

    "

  1. Member of a class defined with the keyword class<\/code> are private<\/code> by default. Members of a class defined with the keywords struct<\/code> (or union<\/code> ) are public<\/code> by default.

    <\/li>

  2. Also, std::is_class<Y>::value<\/code> is true<\/code> for Y being a struct<\/code> and a class<\/code> , but is false<\/code> for an enum class<\/code> .

Another main difference is when it comes to Templates. As far as I know, you may use a class when you define a template but NOT a struct.

template<class T> // OK
template<struct T> // ERROR, struct not allowed here

Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.

"

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.

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

It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.

"

  • . In classes all the members by default are private but in structure members are public by default.

    1. A struct should typically be used for grouping data.

      A class should be used for grouping data and methods that operate on that data.

      In other languages classes and structures may have distinct semantics - ie. objects (instances of classes) may be passed by reference and structures may be passed by value. Note: There are comments associated with this question. See the discussion page to add to the conversation.

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

The other answers have mentioned the private\/public defaults, (but note that a struct is a class is a struct; they are not two different items, just two ways of defining the same item).

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<\/a> .

Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.

class provides permission controls and inherents to enhance decoupling and reusing codes.

for example:http:\/\/en.wikipedia.org\/wiki\/SOLID_%28object-oriented_design%29<\/a>

In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.

The difference between struct<\/strong> and class<\/strong> keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct<\/strong> or union<\/strong> is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct<\/strong> for data and class<\/strong> for code sake. For more information contact other sources.

"

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.

oops 中结构体和类关键字的主要区别在于,结构体中不存在公共和私有成员声明。数据成员和成员函数可以定义为公共、私有和受保护的。

**UPDATE: ** Please ignore this reply. I did not consider the possibility that for the struct, the value was uninitialized but just happened to be 0. There is not an initialization difference between struct and class.


I am seeing another different between structs and classes having to do with default initialization.

struct Foo {
    int a;
};

class Bar {
    int a;
};

class Tester {
    Foo m_Foo = Foo();
    Bar m_Bar = Bar();

public:
    Tester() {}
};

int main() {
    auto myTester = Tester();
}

Run that code and examine myTester. You'll find that for m_Foo, the struct, m_Foo.a has been initialized to 0, but for m_Bar, the class, m_Bar.a is uninitialized. So there does appear to be a difference in what the default constructor does for struct vs. class. I'm seeing this with Visual Studio.

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.

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

Classes are Reference types and Structures are Values types.
When I say Classes are reference types,
basically they will contain the address of an instance variables.

For example:

Class MyClass
{
    Public Int DataMember;  //By default, accessibility of class data members 
                            //will be private. So I am making it as Public which 
                            //can be accessed outside of the class.
}

In main method,
I can create an instance of this class using new operator that allocates memory for this class
and stores the base address of that into MyClass type variable(_myClassObject2).

Static Public void Main (string[] arg)
{
    MyClass _myClassObject1 = new MyClass();
    _myClassObject1.DataMember = 10;

    MyClass _myClassObject2 = _myClassObject1;
    _myClassObject2.DataMember=20;
}

In the above program, MyClass _myClassObject2 = _myClassObject1; instruction indicates that both variables of type MyClass

  1. myClassObject1
  2. myClassObject2

and will point to the same memory location.
It basically assigns the same memory location into another variable of same type.

So if any changes that we make in any one of the objects type MyClass will have an effect on another
since both are pointing to the same memory location.

"_myClassObject1.DataMember = 10;" at this line both the object's data members will contain the value of 10.
"_myClassObject2.DataMember = 20;" at this line both the object's data member will contains the value of 20.
Eventually,

Unlike classes, structures are value types. For example:

Structure MyStructure
{
    Public Int DataMember;  //By default, accessibility of Structure data 
                            //members will be private. So I am making it as 
                            //Public which can be accessed out side of the structure.
}

Static Public void Main (string[] arg)
{
    MyStructure _myStructObject1 = new MyStructure();
    _myStructObject1.DataMember = 10;

    MyStructure _myStructObject2 = _myStructObject1;
    _myStructObject2.DataMember = 20;
}

In the above program,
instantiating the object of MyStructure type using new operator and
storing address into _myStructObject variable of type MyStructure and
assigning value 10 to data member of the structure using "_myStructObject1.DataMember = 10".

In the next line,
I am declaring another variable _myStructObject2 of type MyStructure and assigning _myStructObject1 into that.
Here .NET C# compiler creates another copy of _myStructureObject1 object and
assigns that memory location into MyStructure variable _myStructObject2.

So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue.
That's why we are saying Structures are value types.

So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.

How are we saying that?
And what is the reason behind that?
The answer is Classes.

It can be abstract, sealed, static, and partial and can't be Private, Protected and protected internal.

I found an other difference. if you do not define a constructor in a class, the compiler will define one. but in a struct if you do not define a constructor, the compiler do not define a constructor too. so in some cases that we really do not need a constructor, struct is a better choice (performance tip). and sorry for my bad English.

There are 3 basic difference between structure and class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM