When should you use a class vs a struct in C++?

后端 未结 25 1690
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

相关标签:
25条回答
  • 2020-11-22 00:45

    One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.

    typedef struct
    {
        int messageId;
        int messageCounter;
        int messageData;
    } tMessageType;
    
    void processMessage(unsigned char *rawMessage)
    {
        tMessageType *messageFields = (tMessageType *)rawMessage;
        printf("MessageId is %d\n", messageFields->messageId);
    }
    

    Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.

    0 讨论(0)
  • 2020-11-22 00:45

    You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:

    // C access Header to a C++ library
    #ifdef __cpp
    extern "C" {
    #endif
    
    // Put your C struct's here
    struct foo
    {
        ...
    };
    // NOTE: the typedef is used because C does not automatically generate
    // a typedef with the same name as a struct like C++.
    typedef struct foo foo;
    
    // Put your C API functions here
    void bar(foo *fun);
    
    #ifdef __cpp
    }
    #endif
    

    Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.

    0 讨论(0)
  • 2020-11-22 00:46

    I use structs when I need to create POD type or functor.

    0 讨论(0)
  • 2020-11-22 00:47

    I never use "struct" in C++.

    I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.

    It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.

    E.g.

    class PublicInputData {
        //data members
     };
    
    0 讨论(0)
  • 2020-11-22 00:48

    As others have pointed out

    • both are equivalent apart from default visibility
    • there may be reasons to be forced to use the one or the other for whatever reason

    There's a clear recommendation about when to use which from Stroustrup/Sutter:

    Use class if the class has an invariant; use struct if the data members can vary independently

    However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }). It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.

    0 讨论(0)
  • 2020-11-22 00:49

    As everyone else notes there are really only two actual language differences:

    • struct defaults to public access and class defaults to private access.
    • When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

    But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

    class X
    {
      public:
    
      // ...
    };
    
    struct X
    {
      // ...
    };
    

    (Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

    0 讨论(0)
提交回复
热议问题