Object-Oriented Programming Labs: Understanding Classes and Objects, Exercises of Programming for Engineers

A summary of object-oriented programming labs focused on classes and objects. It covers the definition of a class, separation of interface from implementation, and structure of a class. Three sample programs are included to illustrate the concepts.

Typology: Exercises

2011/2012

Uploaded on 07/25/2012

hun_i
hun_i 🇮🇳

3.7

(3)

54 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
OBJECT ORIENTED PROGRAMMING
LAB 02
CLASSES
Summary
Classes and Objects
Definition of a class
Separation of Interface from the Implementation
Structure of a class
Sample program 1
Sample Program 2
Sample Program 3
Classes and Objects
In today‟s lecture, we will try to learn about the concepts of „classes‟ and „objects‟.
However, we are not going to formally cover the object-oriented programming but only
the ways to manipulate the classes and objects.
We had talked about structures in our previous lectures. In structures, some data variables
are gathered, grouped and named as a single entity. Class and structure are very closely
related. In classes, we group some data variables and functions. These functions normally
manipulate these variables.
Before going ahead, it is better to understand what a class is:
“A class includes both data members as well as functions to manipulate that data”
These functions are called „member functions‟. We also call them methods. So a class
has data (the variables) and functions to manipulate that data. A class is a „user defined‟
data type. This way, we expand the language by creating a new data type. When we
create variables of a class, a special name is used for them i.e. Objects.
“Instances of a class are called objects”
With the definition of class, we have a new data type like int, char etc. Here int i; means
„i‟ is an instance of data type int. When we take a variable of a class, it becomes the
instance of that class, called object.
Definition of a class
Let‟s have a look on the structure of a class. It is very similar to the struct keyword.
Keyword class is used and the braces enclose the definition of the class i.e.
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Object-Oriented Programming Labs: Understanding Classes and Objects and more Exercises Programming for Engineers in PDF only on Docsity!

OBJECT ORIENTED PROGRAMMING

LAB 02

CLASSES

Summary

  • Classes and Objects
  • Definition of a class
  • Separation of Interface from the Implementation
  • Structure of a class
  • Sample program 1
  • Sample Program 2
  • Sample Program 3

Classes and Objects

In today‟s lecture, we will try to learn about the concepts of „classes‟ and „objects‟. However, we are not going to formally cover the object-oriented programming but only the ways to manipulate the classes and objects.

We had talked about structures in our previous lectures. In structures, some data variables are gathered, grouped and named as a single entity. Class and structure are very closely related. In classes, we group some data variables and functions. These functions normally manipulate these variables.

Before going ahead, it is better to understand what a class is:

“A class includes both data members as well as functions to manipulate that data”

These functions are called „member functions‟. We also call them methods. So a class has data (the variables) and functions to manipulate that data. A class is a „user defined‟ data type. This way, we expand the language by creating a new data type. When we create variables of a class, a special name is used for them i.e. Objects.

“Instances of a class are called objects”

With the definition of class, we have a new data type like int, char etc. Here int i; means „i‟ is an instance of data type int. When we take a variable of a class, it becomes the instance of that class, called object.

Definition of a class

Let‟s have a look on the structure of a class. It is very similar to the struct keyword. Keyword class is used and the braces enclose the definition of the class i.e.

class name_of_class{ // definition of class }

The new data type i.e. classes helps us to have grouped data members and member functions to manipulate the data. Consider a structure of Date having data members i.e. year, month and day. Now we can declare a variable of structure Date and use dot operator to access its members i.e.

Date myDate; myDate.month=3;

We have to use the name of the object, a dot operator and the data member of structure to be accessed. The data members are of normal data types like int, float, char etc. Other data types can also be used.

Let‟s consider an example of Date Class shown in the following statement.

class Date{ int Day; int month; int year; };

Now we will take its object in the fashion given below:

Date myDate;

Separation of Interface from the Implementation

To access the data members of the class, we will again use dot operator. Before going ahead, we will see what is the difference between struct and class. It is the visibility of the data members that differentiates between struct and class. What does the word „visibility‟ mean? Consider an example of payroll system. We have stored the tax rate i.e. 5% in a variable i of type int. Later, we used the same i in a loop and changed the value of tax rate unintentionally. Now the calculation of the pay in the end will not provide the correct results. To avoid this problem, we can tag the tax rate variable as int tax_rate ;. But this variable again is visible in the whole program and anyone can change its value. The data is open and visible to every part of the program, creating a big problem. In normal programming, we will like to see the data encapsulated. It means that data is hidden somewhere. However, it can be used. Let‟s consider a real world problem to understand it. Most of us have wrist-watches. To have accuracy, it is necessary to adjust the time. How can we do that? We can change the time by using the button that is provided on one side of the watch. This is a kind of encapsulation. We can see the hands of the watch but cannot touch them. To change their position we used the button.

Normally, the data in a class is kept private. If we make the data public, it is same as structure and anyone can access this data. On the other hand, the functions which we have written to manipulate this data, are kept as public. These methods can be called from outside the class i.e. from the main program. These are the member functions of the class. The difference between these and the ordinary functions is that they are part of class. Moreover, they can see the private data members of the class and also manipulate them.

We have made the data members private in the Date class. In the program, we take an object of Date class as Data myDate ;. myDate is a variable of type Date. Now if we say myDate.month = 3; this statement will be illegal as the month is a private data member of the Date class. Now try to understand this concept. You can think class as a box having different things in it. How can we touch inside the box? We have a window and can see only those things that are visible through this window. Those things which we cannot see from the window, can not be accessed from outside. Day, month and year are somewhere inside the box and are not visible through the window. Now we want to assign some values to these data members. For this purpose, we will define a member function in the class in the public section. Being present in public section, it will be visible through the window. As this is the member function, it can see and manipulate the private data of the class. Now it‟s a two-step process. We can see the public functions and public functions can view the private data members of the class. We will write a function to set the value to the month. We cannot write it as myDate.month = 10 ;. So our function prototype will be as:

void setMonth(int month)

and we may call this function as:

myDate.setMonth(10);

Now the function setMonth will assign the value 10 to month data member of the object myDate. The same thing will be applicable if we want to print the date. We can write a public function print and can access it as:

myDate.print();

The function print can see the private data members. So it will format the date and print it. In structures, the data members are public by default. It means that these are visible to all and anyone can change them. Is there any disadvantage of this? Think about the date. What may be the valid values of the day? Can we have a day less than zero or greater than 31. So the minimum and maximum values of the day are 1 and 31 respectively. Similarly, in case of month, the minimum and maximum values may be 1 and 12. We can assign different values to year like 1900, 2002 etc. If we are using Date structure instead of a class, we can write in the program as myDate.month=13; and the month will be set to 13. So the date will become invalid. We may want that other programmers also use this structure. But other programmers may put invalid values to the data-member as these

are publicly accessible. Similarly in structures, everything is visible i.e. what are the names of the data members. How are these manipulated?

Now we want that only those things should be visible which we want to show and those things which we want to hide should not be visible We can get this by using the private and public in the classes. Public becomes the interface of the class, what we want to show to others. With the use of public interface, the objects can be manipulated. Private becomes the inside of the class i.e. the data members, the implementation. We don‟t want to show the implementation of our classes to others. This is the concept of separation of interface from implementation. It is a crucially important concept in modern programming. We have separated the interface from the implementation. As long as the interface remains the same, the implementation can be changed. Let‟s think about it in real world. The example from the automobiles sector can help us understand further. The production of cars in the world started in the late 18th century and early 19th century. Let‟s compare these early or prototype cars with today‟s modern ones. There is a big difference between the old and new cars. Technology has changed. Now what is still common in both the types. Steering, clutch, brakes and accelerator pads are still the basic components of a car. So the interface is same. The internal functionality can be changed. To turn the car, old cars used rod mechanisms and modern cars have the microprocessor to do this job. Our physical action is same in both the cases. The interface i.e. steering is same and also the effect that wheels have turned to right is the same too. The internal implementation has completely changed. The old combustion engine cannot be compared with the state-of-the technology based modern engines. But the interface is the same i.e. we turn the key to start an engine. This concept of separation of implementation from interface comes into our programming. We have written a program today to calculate the orbital time of moon around the earth. In today‟s physics, we have formula to calculate this. We have defined the interface calculateOrbitalTime(). This is a function that will calculate the orbital time of moon around earth. This formula may prove wrong after some time. Now what can we do? Despite the change in the implementation, interface remains the same i.e. the name of the function is same. Now when the program will use this function, it gets the correct result as we have implemented the new formula inside the function. Moreover, the main program does not need to be changed at all. Being a very neat concept, it can be used while dealing with objects and classes.

Sample program 1

/A C++ program that can add two numbers:/

#include<iostream.h> #include<conio.h>

class addNum { private: int x; int y;

void setX(int); void setY(int); int add(); int disp(); }; void Test::setX(int x1) { x=x1; } void Test::setY(int y1) { y=y1; } int Test::add() { z=x+y; }

int Test::disp() { return z; }

main() { clrscr(); Test t; int Xm,Ym,x,y; cout<<"Enter Value of X : "; cin>>Xm; t.setX(Xm);

cout<<"Enter Value of Y : "; cin>>Ym; t.setY(Ym); t.add(); y=t.disp(); cout<<y; getche(); }

Sample Program 3

Let‟s see the example of Date class in detail.

class Date { public: void display(); Date(int, int, int); private: int day, month, year; };

Date is the name of new user defined data type. After the braces, we have written the keyword public. In this section, we will define the interface of the class. We have declared a function display() which will print the date on the screen. Another function Date(int day, int month, int year) is declared. The name of this function is same as the name of the class, having no return type. This function is called constructor. Then we write the keyword private and define the implementation of the class. Here we have three variables i.e. day, month and year of type int. In the end closing braces and the semi-colon. This is the definition of user defined data type i.e. class. It will not occupy any memory space as it has no data currently. It is the same as we write in case of „int‟. It does not occupy any memory but when we say int I, the memory is reserved for i. The class is a „user defined data‟ type. Now in our program, when we write Date myDate ; an instance of the class is created i.e. an object. Object reserves space in the memory. Object will have these data members. What about the „functions‟? For a moment, we can say that functions are also in the memory.

We want to use this class in our program and display the date using the display() function. We have written the prototype of the display() function in the class without defining the display() function yet. A special way is used to define these functions. We will write the name of the class, followed by two colons and the name of the function. The rest is same as we used to do with ordinary functions.

Date::display() { // the definition of the function cout << “The date is “ << day << “-“ << month << “-“ << year << endl; }

You might have noted the difference in the first line. The double colon is called scope resolution operator. It resolves the scope and tells that this function belongs to whom. In this case, the ( Date::display()) ) tells that the display() function belongs to the Date class. So the scope resolution is required. In a way, consider it as function is defined inside the class. If you have private function, even then the definition mechanism is same. We will define the function outside of the class. Even then it will not be visible as its visibility is private. The way to define the member functions is, class name, double colon, name of the function including arguments and then the body of the function. Can we define the function inside the class? Yes we can. When we write the function inside the class, the compiler tries to treat that function as inline function. As a good programming practice,

date1.setMonth(12); date1.setYear(2002); date1.display();

// Manipulating date2 object date2.setDay(15); date2.setMonth(1); date2.setYear(2003); date2.display();

We have declared three objects of type Date. All these objects have data members day, month and year. When we call a function, that is defined in class, with some object name, it uses the data of that object which is calling the function. Suppose, when we write date1.setMonth(12); it will manipulate the data of object date1. Similarly when we say date2.display() , the function is defined inside the class. However, it will use the data of date2 object. Remember that we will always call these member functions by referring to some specific object. We can call these functions with date1, date2 or date3 respectively. We will never call these functions referring to a class that is we cannot say Date.display(); It is illegal. The functions of getting data from objects and setting data of objects are standard. So we normally use the word „set‟ for setting the data and „get‟ for getting the data. It is a matter of style. You can call it whatever you want. But it will be a bad idea to name a function print() and it is setting the value of month. It will work but in a very confused manner. If we want to write a function to set month, the logical choice of the function name is setMonth(int). Similarly, setDay(int) and setYear(int) will be used to set the day and year respectively. If we want to get the values of these data members, the logical choice will be getDay(), getMonth() and getYear(). The names are selfexplanatory.

These functions are defined as member functions of the class. They are put in the public section of the class and constitute the public interface of the class. These will be visible from outside the class. Normally they manipulate the data that is hidden inside the class i.e. in the private section of the class. No need to show the working of the functions only its name, argument and the return type is told to the user. User of the class is our program.

Here is the complete code of the Date class.

/* A sample program with the Date class. Set methods are given to set the day, month and year. The date is also diplayed on the screen using member function. */

#include <iostream.h> // defining the Date class class Date{ // interface of the class public: void display(); // to display the date on the screen

void setDay(int i); // setting the day void setMonth(int i); // setting the month void setYear(int i); // setting the year // hidden part of the class private: int day, month, year; }; // The display function of the class date void Date::display() { cout << "The date is " << day << "-" << month << "-" << year << endl; } // setting the value of the day void Date::setDay(int i) { day = i; } // setting the value of the month void Date::setMonth(int i) { month = i; } // setting the value of the year void Date::setYear(int i) { year = i; } // Main program. We will take two date objects, set day, month, year and display the date. int main() { Date date1,date2; // taking objects of Date class // setting the values and displaying date1.setDay(1); date1.setMonth(1); date1.setYear(2000); date1.display(); // setting the values and displaying date1.setDay(10); date1.setMonth(12); date1.setYear(2002); date1.display(); }

The output of the program is:

The date is 1-1-