next up previous contents index
Next: Constructors Up: C++ Previous: A C++ program   Contents   Index


Classes in C++ are natural extensions of structures in C. In fact, in some sense, a class is simply a structure (which already has various data members) extended to also include subroutines in the basic structure definition. In the context of classes, subroutines are called methods.

Here is an example of a class, called animal, which has two data attributes, a string name and a boolean warm_blooded, and with two methods, get_info and print_info. The basic class definition is in a header file animal.h:

// file animal.h
class animal {
  char name[50];
  bool warm_blooded;
  void get_info(void);
  void print_info(void);
while the methods are in the file animal.cpp:
#include <iostream.h>
#include <string.h>
#include "animal.h"
char newline;

void animal::get_info(void) {
  char answer[10];
  int name;
  cout << endl << "Enter the name: ";
  cin.get(animal::name, 50, '\n');
  cout << "Is the animal warm-blooded (yes or no) ";
  cin.get(answer, 10, '\n');
  warm_blooded = (strcmp(answer, "yes") == 0) ? true : false;

void animal::print_info(void) {
  cout << endl << "name: " << name << endl;
  if (warm_blooded == true) {
    cout << "The animal is warm blooded" << endl;
  else {
    cout << "The animal is not warm blooded" << endl;
Note the use of the notation class::method to define the methods. Also note the availability of the data attributes name and warm_blooded right within the methods. Finally, note that data attributes and methods must be declared in the class definition as public if they are to be accessible outside of the class.

An example of a program that uses this class is

// file jane.cpp
#include <iostream.h>
#include "animal.h"

int main(void) {
  animal jane;
  return (0);
To compile this program, first compile animal.cpp as
  c++ -c animal.cpp
to create an object file containing the class definition, and then
  c++ jane.cpp animal.obj
to compile and run the program. Note the dot notation object.method() to access methods, just as is used to access members of a structure in C.
next up previous contents index
Next: Constructors Up: C++ Previous: A C++ program   Contents   Index