Export (0) Print
Expand All

class

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

class [tag [: base-list ]]
{
   member-list
} [declarators];
[ class ] tag declarators;

The elements of a class definition are as follows:

tag
Names the class type. The tag becomes a reserved word within the scope of the class.
base-list
Specifies the class or classes from which the class is derived (its base classes). Each base class's 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.
member-list
Declares members or friends of the class. Members can include data, functions, nested classes, enums, bit fields, and type names. Friends can include functions or classes. Explicit data initialization is not allowed. A class type cannot contain itself as a nonstatic member. It can contain a pointer or a reference to itself. See the virtual keyword and the member-access table in Controlling Access to Class Members for more information.
declarators
Declares one or more objects of the class type.

Example

// 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
{
public:
   dog()
   {
      _legs = 4;
      _bark = true;
   }

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

private:
   string _dogSize, _earType;
   int _legs;
   bool _bark;

};

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

   string getColor()
   {
      return _color;
   }

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

protected:
   string _color, _earLength, _earType;
};

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

For more information, see the following topic:

See Also

C++ Keywords | Classes, Structures, and Unions

Show:
© 2014 Microsoft