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. docsity.com 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. docsity.com 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; docsity.com int z; public: int add(int, int); int disp(); }; int addNum::add(int x1,int y1) { x=x1; y=y1; z=x+y; } int addNum::disp() { return z; } main() { clrscr(); addNum a; int r; a.add(10,20); a.disp(); r=a.disp(); cout<<r; getche(); } Sample Program 2 /*A C++ program to add two numbers. Please note down the difference between these two examples. In example 1, the numbers to be added are passed as function arguments, whereas in the second example, the program is interactive, it ask for numbers to be added.*/ #include<iostream.h> #include<conio.h> class Test { private: int x; int y; int z; public: docsity.com 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. docsity.com 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 docsity.com 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-2000 docsity.com The date is 10-12-2002 Exercises: 1- Using classes write a C++ program that can display a set of numbers. The user is asked for a start/end values for the set and the difference between two consecutive numbers. E.g. Range: 1 – 10 Difference: 2 Output: 1 3 5 7 9 2- Using classes write a C++ program that can calculate the area of a triangle. The formula for finding the area is: ½ * base * altitude. docsity.com