This documentation is archived and is not being maintained.

class (C++)

The class keyword declares a class type or defines an object of a class type.

[template-spec] class [ms-decl-spec] [tag [: base-list ]]
} [declarators];
[ class ] tag declarators;



Optional template specifications. For more information, refer to Template Specifications.


The class keyword.


Optional storage-class specification. For more information, refer to the __declspec keyword.


The type name given to the class. The tag becomes a reserved word within the scope of the class. The tag is optional. If omitted, an anonymous class is defined. For more information, see Anonymous Class Types.


Optional list of classes or structures this class will derive its members from. See Base Classes for more information. Each base class or structure name can be preceded by an access specifier (public, private, protected) and the virtual keyword. See the member-access table in Controlling Access to Class Members for more information.


List of class members. Refer to Class Members for more information.


Declarator list specifying the names of the class. Declarator lists declare one or more instances of the class type. Declarators may include initializer lists if all data members of the class are public. This is more common in structures, whose data members are public by default, than in classes. See Overview of Declarators for more information.

For more information on classes in general, refer to one of the following topics:

For information on managed classes and structs, see Classes and Structs

// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.

#include <iostream>
#include <string>
#define TRUE = 1
using namespace std;

class dog
      _legs = 4;
      _bark = true;

   void setDogSize(string dogSize)
      _dogSize = dogSize;
   virtual void setEars(string type)      // virtual function
      _earType = type;

   string _dogSize, _earType;
   int _legs;
   bool _bark;


class breed : public dog
   breed( string color, string size)
      _color = color;

   string getColor()
      return _color;

   // virtual function redefined
   void setEars(string length, string type)
      _earLength = length;
      _earType = type;

   string _color, _earLength, _earType;

int main()
   dog mongrel;
   breed labrador("yellow", "large");
   labrador.setEars("long", "floppy");
   cout << "Cody is a " << labrador.getColor() << " labrador" << endl;