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

后端 未结 30 3212
盖世英雄少女心
盖世英雄少女心 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:12

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

提交回复
热议问题