2010-06-07

C++: Class vs Struct (clarification)

Classes and structures are the same thing in C++ except that the struct's default visibility is public, the class' is private. To highlight the equivalence: struct can have member functions, constructors, overloaded operators, virtual member functions, private members. Classes can have public data members. It is really just about the default visibility of members.

Let's see equivalent examples, let's talk about the philosophy later...

struct Vector {
    double x,y;
};

class Vector {
public:
    double x,y;
};

and

class Vector {
public:
    Vector(double x_, double _y);
    Vector& SetXY(double x_,double y_);
    double GetX() const;
    double GetY() const;
    //...
private:
    double x,y;
};

struct Vector {
    Vector(double x_, double _y);
    Vector& SetXY(double x_,double y_);
    double GetX() const;
    double GetY() const;
    //...
private:
    double x,y;
};

In my opinion class's default visibility is not very useful because we used to start the class definition with the public members to ease the interpretation of it for the users of our class.

The big difference is in the intent of the declaration. If we want to create a composite behavior-less data unit that is passed around, then we should use the struct keyword so the reader will know what's going on. If you want to create an object which fulfills an abstract concept and has a behavior, then you should define a class.

IMPORTANT: If you use class you should really take care about the basic requirements like hiding data members (making them private or protected in order to maintain principle of local responsibility), providing type-invariant safe public methods, disabling copy semantics if not needed explicitly, and so on ...

2 comments:

  1. thanks for that...
    I've been looking at c++ struct as a weird thing, until reading this, then checked syntax description at cppreference... it has inheritance too...
    What you think why struct has changed to this from the one we knowed in C?

    ReplyDelete
  2. I think the 'class' keyword which they created was able to "emulate" the old style 'struct' which gave the idea that they could be the same...

    I wonder... I suspect that this was not a pure accident but some kind of goal. The C++ inventors wanted to keep and train the existing C community.

    ReplyDelete