A Simple Class :
Our first program contains a class and two objects of that class. Although it’s simple, the programdemonstrates the syntax and general features of classes in C++.
Here’s 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;
}
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. (This may
sound like Greek, but we’ll see what these terms mean as we go along.)
Placing data and functions together into a single entity is a central idea in object-oriented
programming.
No comments:
Post a Comment