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

后端 未结 30 3770
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:38

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 d

30条回答
  •  深忆病人
    2020-11-21 06:08

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

提交回复
热议问题