This module explores some of the basic concepts of building classes in C++ and introduces you to the internal workings of the class construct.
We have learned about structures, which provide a way to group data elements. We have examined functions, which organize program actions into named entities. In this module, we will put these ideas together to create classes and introduce several classes, starting with simple ones and working toward more complicated examples. In addition, we will focus first on the details of classes and objects. At the end of the module we will take a wider view, discussing what is to be gained by using the OOP approach.
A Simple Class
Our first program contains a class and two objects of that class. Although it is simple, the program demonstrates the syntax and general features of classes in C++. Here is the listing for the SMALLOBJ program.
// smallobj.cpp
// demonstrates a small, simple object
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class smallobj //define a class{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data{
somedata = d;
}
void showdata() //member function to display data{
cout << "Data is " << somedata << endl;
}
};
int main(){
smallobj s1, s2; //define two objects of class smallobj
s1.setdata(1066); //call member function to set data
s2.setdata(1776);
s1.showdata(); //call member function to display data
s2.showdata();
return 0;
}
Data and Functions
The class smallobj defined in this program contains one data item and two member functions. The two member functions provide the only access to the data item from outside the class. The first member function sets the data item to a value, and the second displays the value. Placing data and functions together into a single entity is a central idea in object-oriented programming.
This is shown in Figure 3.1.
Figure 3-1: Data and Functions
Example of Class Rectangle in C++
class CRectangle {
int x, y;
public:
void setValues (int,int);
int area (void);
} rect;