A class is a user defined abstract data type that further expands upon the concept of a structure but instead of containing just data, it also includes functions.
In OO parlance, functions within a class are referred to as methods.
The concept of enclosing data and functions together within a single entity is referred to as Encapsulation.
Strictly speaking, as far as the compiler is concerned, the only difference between a structure and a class is that of accessibility (aka visibility). A structure's members are all public by default, whereas a class's members are all private by default. However, it is normal programming convention not to mix the two up and therefore structures are generally used for data (or POD: Plain Old Data), and classes are used for objects.
A class consists of three elements:
- Identity
- Name for the class
- Attributes
- Data members
- Methods
- Function members
A class is akin to a blueprint or plan of how to make an object, that declares its attributes (member data types) and methods.
A class is declared by use of the keyword class
- followed by the user defined identity name for the class (akin to a primitive data type, e.g. int)
- followed by the class members enclosed within a set of { curly braces }
- followed by optional object identifiers
- followed by a semi-colon ;
Syntax:
class identity {
public:
members ;
private:
members ;
protected:
members ;
} objects ;
The keywords public, private and protected are known as the access specifiers, which define the level of visibility of a class's members.
Once the class has been declared, an object is declared just like any other data type (e.g. int x;).
Extremely simple Class example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std ; class Triangle { public: float width ; float height ; float area(){ return ((width * height) / 2) ; } } ; int main () { Triangle myTriangle ; myTriangle.width = 5 ; //member access using the .dot operator myTriangle.height = 6 ; cout << "Triangle area: " << myTriangle.area() << endl ; return 0; } |
Compile & Run:
Triangle area: 15 |
The above example is overly simplified to show a function being used within a class. Normally all attributes (in this case the two floats on lines 7 and 8) should be private to ensure that only the object itself is responsible for any changes of its own data.
An object is said to be instantiated, by declaring a new identifier against the class's identity (i.e. the abstract data type), as per line 17 above.