Jiahonzheng's Blogs

Struct vs Class in C++

字数统计: 213阅读时长: 1 min
2018/04/03 Share

In C++, structure is same as class except the following differences.

  • Members of a class are private by default and members of struct are public by default.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    // Program 1
    #include <iostream>

    class Test {
    int x; // x is private
    };

    int main() {
    Test t;
    t.x = 20; // compiler error because x is private
    getchar();
    return 0;
    }

    // Program 2
    #include <iostream>

    struct Test {
    int x; // x is public
    };

    int main() {
    Test t;
    t.x = 20; // works fine because x is public
    getchar();
    return 0;
    }
  • When deriviing 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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    // Program 3
    #include <iostream>

    class Base {
    public:
    int x;
    };

    class Derived : Base {}; // is equivalent to "class Derived : private Base {};"

    int main() {
    Derived d;
    d.x = 20; // compiler error because inheritance is private
    getchar();
    return 0;
    }

    // Program 4
    #include <iostream>

    class Base {
    public:
    int x;
    };

    struct Derived : Base {}; // is equivalent to "struct Derived : public Base{};"

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

CATALOG