class

Example by: Ira Oldham, References: Savitch eighth edition, section 10.2; Gaddis seventh edition, section 13.2

The keywords struct and class differ only that struct defaults to public, while class defaults to private. Of course, you can change between private and public in either one with public: and private:

1  class Sum
2  {
3    int a;
4    int b;
5  public:
6    int getA() {return a;}
7    int getB() {return b;}
8    void putA(int value) {a = value;}
9    void putB(int value) {b = value;}
10   int sum();
11 };
12 int main(void)
13 {
14   Sum x;
15   int result;
16   x.putA(3);
17   x.putB(4);
18   result = x.sum();
19   cout << "x.a: " << x.getA() << endl;
20   cout << "x.b: " << x.getB() << endl;
21   cout << "sum: " << x.sum()  << endl;
22   return 0;
23 }
24 int Sum::sum()
25 {
26   return a + b;
27 }
x.a: 3
x.b: 4
sum: 7

A class and a struct are almost the same thing, differing only in the default initial access of public in struct, and private in class. While the are very similar, they are used for different purposes.

When you want to just use public data, use struct. When you want to build a class use class. Important style rules: