Classes and Objects in Oriented Object Programming C++

An object is said to be an instance of a class, in the same way my 1954 Chevrolet is an instance of a vehicle.

In SMALLOBJ, the class—whose name is smallobj—is defined in the first part of the program. Later, in main(), we define two objects—s1 and s2—that are instances of that class. Each of the two objects is given a value, and each displays its value. Here’s the output of the program:
Data is 1066 ←object s1 displayed this
Data is 1776 ←object s2 displayed this.

We’ll begin by looking in detail at the first part of the program—the definition of the class smallobj. Later we’ll focus on what main() does with objects of this class.
Defining the Class Here’s the definition (sometimes called a specifier) for the class smallobj, copied from the SMALLOBJ listing:

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 << “\nData is “ << somedata; }
};

The definition starts with the keyword class, followed by the class name—smallobj in this example. Like a structure, the body of the class is delimited by braces and terminated by a semicolon. (Don’t forget the semicolon. Remember, data constructs such as structures and classes end with a semicolon, while control constructs such as functions and loops do not.)

Post a Comment

0 Comments