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]; public: 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(newline); cin.get(answer, 10, '\n'); cin.get(newline); 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; jane.get_info(); jane.print_info(); return (0); }To compile this program, first compile animal.cpp as
c++ -c animal.cppto create an object file containing the class definition, and then
c++ jane.cpp animal.obj janeto 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.