Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) class

 

class is a keyword to start a class declaration. A class is a user-defined data type with multiple elements and access levels. A class has data members, member functions and free functions.

 

The class keyword also be used to create a template function.

 

 

 

 

 

C++98C++11 Example class

 

class MyClass
{
  public: int mValue;
};

int main()
{
  MyClass m;
  m.mValue = 10;
}

 

Don't forget the semicolon at the end of the class definition!

 

 

 

 

 

C++98C++11 Class elements

 

A class can have many types of members:

 

struct MyClass
{
  //public by default
  void SetX(const int x) { m_x = x; } //A member function
  int m_x;                            //A data member
};

 

All classes have a four special methods called the Big Four: default constructor, destructor, copy constructor and copy assignment operator:

 

struct NoClass {}; //Do all classes really have a constructor, destructor,
                   //copy constructor and copy-assignment operator?

 

This class called NoClass is silently converted by your compiler to the following (from [1]):

 

struct NoClass
{
  NoClass()                              //Default constructor                
  {
    //something
  }
  NoClass(const NoClass& rhs)            //copy constructor
  {
    //something
  }
  ~NoClass()                             //Default destructor
  {
    //something
  }
  NoClass& operator=(const NoClass& rhs) //copy-assignment operator
  {
    //something
  }
};

 

Know what functions C++ silently writes and calls [1].

 

 

 

 

 

C++98C++11 Class access levels

 

A class has three different access levels: public, private and protected. A class' default for functions and variables is private. This is the only (!) difference with a struct, which has public as its default access level.

 

struct MyClass
{
  //public by default, so the keyword public below is redundant
  public   : int m_public;
  protected: int m_protected;
  private: : int m_private;
};

int main()
{
  MyClass m;
  m.m_public    = 0; //OK, this member variable is public
  m.m_protected = 0; //Not allowed, this member variable is protected
  m.m_private   = 0; //Not allowed, this member variable is private
}

 

 

 

 

 

C++98C++11 Class types

 

Examples of class types are:

 

 

 

 

 

C++98C++11 Class design

 

See class design for some guidelines on class design.

 

Design patterns are standarized class designs to achieve a certain goal, often involving multiple classes.

 

 

 

 

 

C++98C++11 Example classes

 

 

 

 

 

 

References

 

  1. Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 5: 'Know what functions C++ silently writes and calls'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict