Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Objects and Classes in Object Oriented Programming., Slides of Object Oriented Programming

Helpful in learning object oriented programming.Easy to understand.

Typology: Slides

2018/2019

Uploaded on 09/28/2019

urvah-javed
urvah-javed 🇵🇰

5

(1)

1 document

1 / 73

Toggle sidebar

Related documents


Partial preview of the text

Download Objects and Classes in Object Oriented Programming. and more Slides Object Oriented Programming in PDF only on Docsity! Object Oriented Programming Chapter 06: Objects and Classes Engr. Rashid Farid Chishti [email protected] https://sites.google.com/site/chishti International Islamic University H-10, Islamabad, Pakistan http://www.iiu.edu.pk I t r ti l I l i i r it - , I l , i t tt :// .ii . . 1 Class Object Introduction  Previously, programmers starting a project would sit down almost immediately and start writing code.  As programming projects became large and more complicated, it was found that this approach did not work very well. The problem was complexity.  Large programs are probably the most complicated entities ever created by humans.  Because of this complexity, programs are prone to error, and software errors can be expensive and even life threatening (in air traffic control, for example).  Three major innovations in programming have been devised to cope with the problem of complexity. 2 Class  A class serves as a plan, or template. It specifies what data and what functions will be included in objects of that class.  Defining the class doesn’t create any objects, just as the type int doesn’t create any variables.  A class is thus a description of a number of similar objects. 5 functions data A class encapsulates attributes and functions #include <iostream> #include <stdlib.h> using namespace std; class student // define a class (a concept) { private: int age; // class data (attributes) public: void set_age(int g) // member function (method) { // to set age age = g; } void show_age() // member function to display age { cout << "I am " << age << " Years Old."<< endl; } }; 6 A Simple Class (1/2) int main() { student Ali, Usman; // define two objects of class student Ali.set_age(21); // call member function to set age Usman.set_age(18); Ali.show_age(); // call member function to display age Usman.show_age(); system("PAUSE"); return 0; } 7 A Simple Class (2/2) Defining the Class  The definition starts with the keyword class, followed by the class name—student in this Example.  The body of the class is delimited by braces and terminated by a semicolon.  An object has the same relationship to a class that a variable has to a data type.  A key feature of object-oriented programming is data hiding. it means that data is concealed within a class so that it cannot be accessed mistakenly by functions outside the class.  The primary mechanism for hiding data is to put it in a class and make it private. 10 Defining the Class  Private data or functions can only be accessed from within the class.  Public data or functions, on the other hand, are accessible from outside the class.  The data member age follows the keyword private, so it can be accessed from within the class, but not from outside.  Member functions (also called methods or messages) are functions that are included within a class.  There are two member functions in student class: set_age() and show_age(). 11 Defining the Class  Because  set_age() and  show_age()  follow the keyword  public, they can  be accessed from  outside the class.  In a class the functions  do not occupy memory until an object of the class is created. 12 void show_info() { // display data cout << "Company = " << company_name.data() << endl; cout << "Model = " << model_number.data() << endl; cout << "EMI = " << emi_number.data() << endl; cout << "Cost = Rs." << cost << endl; } }; int main() { mobile m1; // define object of class mobile m1.set_info("QMobile", "Noir A950", "don’t know :)", 25000.0F); // call member function m1.show_info(); // call member function system("PAUSE"); return 0; } 15 Using Mobile Phone as an Object (2/2)  If you were designing an inventory program you might actually want to create a class something like mobile.  It’s an example of a C++ object representing a physical object in the real world—a mobile phone.  Standard C++ includes a new class called string.  Using string object, you no longer need to worry about creating an array of the right size to hold string variables.  The string class assumes all the responsibility for memory management. Using Mobile Phone as an Object 16 #include <iostream> #include <stdlib.h> using namespace std; class Height{ // A Height class private: int feet; float inches; public: void set(int ft, float in){ feet = ft; inches = in; } void get(){ // get height information from user cout << "\nEnter Your Height Information "<<endl; cout << "Enter feet: ";cin >> feet; cout << "Enter inches: "; cin >> inches; } void show(){ // display height information cout << "Height = "<< feet << " feet and " << inches << " inches."<<endl; } 17 Using Class to Represent Height (1/2) #include <iostream> // A Constructor Example #include <stdlib.h> using namespace std; class House{ private: double area; // area in square feet public: House() : area(1000){ // a zero (no) argument constructor cout<< "House Created \n"; } void set_area(double a) { area = a; } double return_area() { return area; } void get_area(){ // get area info from user cout << "What is the area of House in Square Feet:"; cin >> area; } }; 20 Constructors: House Example (1/2) int main() { House H1, H2; // define objects and calls constructor cout << "default area of House H1 is = " << H1.return_area() << endl; cout << "default area of House H2 is = " << H2.return_area() << endl; H1.set_area(1500); H2.get_area(); cout << "Now Area of House H1 is = " << H1.return_area() << " Square Feet"<<endl; cout << "Now Area of House H2 is = " << H2.return_area() << " Square Feet"<<endl; system("PAUSE"); return 0; } 21 Constructors: House Example (2/2) #include <iostream> // for cin and cout #include <stdlib.h> // for rand(), srand() and system() #include <time.h> // for time() using namespace std; class Dice{ private: int number; public: Dice():number(1){ // zero (no) argument constructor // Sets the default number rolled by a dice to 1 // seed random number generator with current system time srand(time(0)); } int roll() //Function to roll a dice. { // This function uses a random number generator to randomly // generate a number between 1 and 6, and stores the number // in the instance variable number and returns the number. number = rand() % 6 + 1; return number; } 22 Constructors: A Dice Example (1/2) #include <iostream> using namespace std; class House{ private: double area; // area in square feet public: House() : area(1000) // a zero argument const. { cout << "House Created \n"; } ~House() // a zero (no) argument destructor { cout<< "House has been destroyed \n"; } double return_area() { return area; } }; int main(){ House H1; cout << "default area of " << "House H1 is = " << H1.return_area() << endl; system("PAUSE"); return 0; } 25 Destructors: House Example // A Constructor Example #include <iostream> using namespace std; class House{ private: double area; // area in square feet public: House() : area(1000) // a zero (no) argument constructor { cout << "House Created \n"; } ~House() // a zero (no) argument destructor { cout<< "House has been destroyed \n"; } }; void Create_House(){ House aHouse; cout << "End of function" << endl; } int main(){ Create_House(); Create_House(); system("PAUSE"); return 0; } 26 Destructors: House Example 2 #include <iostream> #include <string.h> using namespace std; class String{ public: char* p;// data String() : p(NULL){ // a zero (no) argument constructor cout<<"No Argument Constructor was called"<<endl; } String(char* src){ // a one argument constructor int size = strlen(src); // find string length cout<<"Requesting more Memory to OS"<<endl; p = new char[size+1]; // dynamic memory allocation strcpy(p,src); // copy string } ~String(){ // destructor cout<<"Returning Memory to OS"<<endl; delete [] p; // return occupied memory to OS } }; 27 Destructors: A String Example (1/2) // englcon.cpp constructors, adds objects using member function #include <iostream> #include <stdlib.h> using namespace std; class Distance // English Distance class { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { cout<< "No Arguments Constructor has been Called \n" ; } Distance(int ft, float in) : feet(ft), inches(in) { cout<< "Two Arguments Constructor has been Called \n" ; } void getdist(){ // get length from user cout << "\nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } 30 Objects as Function Arguments (1/3) void showdist(){ // display distance cout << feet << "\'-" << inches << '\"'; } void add_dist( Distance, Distance ); // declaration }; // member function is defined outside the class void Distance::add_dist(Distance d1, Distance d2) { inches = d1.inches + d2.inches; // add the inches feet = 0; // (for possible carry) if(inches >= 12.0){ // if total exceeds 12.0, inches -= 12.0; // then decrease inches by 12.0 feet++; // and increase feet by 1 } feet += d1.feet + d2.feet; // add the feet } 31 Objects as Function Arguments (2/3) int main() { Distance dist1, dist3; // Calls no args. constructor Distance dist2(11, 6.25); // Calls two args. constructor dist1.getdist(); // get dist1 from user dist3.add_dist(dist1, dist2); // dist3 = dist1 + dist2 // display all lengths cout << "\ndist1 = "; dist1.showdist(); cout << "\ndist2 = "; dist2.showdist(); cout << "\ndist3 = "; dist3.showdist(); cout << endl; system("PAUSE"); return 0; } 32 Objects as Function Arguments (3/3) Objects as Arguments  Since add_dist() is a member function of the Distance class, it can access the private data in any object of class Distance supplied to it as an argument, using names like dist1.inches and dist2.feet.  In the following statement dist3.add_dist(dist1, dist2);  add_dist() can access dist3, the object for which it was called, it can also access dist1 and dist2, because they are supplied as arguments.  When the variables feet and inches are referred to within this function, they refer to dist3.feet and dist3.inches.  Notice that the result is not returned by the function. The return type of add_dist() is void. 35 Objects as Arguments  The result is stored automatically in the dist3 object.  To summarize, every call to a member function is associated with a particular object (unless it’s a static function; we’ll get to that later).  Using the member names alone (feet and inches), the function has direct access to all the members, whether private or public, of that object.  member functions also have indirect access, using the object name and the member name, connected with the dot operator (dist1.inches or dist2.feet) to other objects of the same class that are passed as arguments. 36 Member functions of dist3 can refer to its data directly. Data in objects passed as arguments is referred to with the dot operator. dist1. feet dist2. feet dist1.inches dist2.inches void showdist(){ //display distance cout << feet << "\'-" << inches << '\"'; } }; int main(){ Distance dist1; // calls no arguments constructor Distance dist2(11, 6.25); // calls two-arg constructor Distance dist3(dist2); // calls default copy constructor Distance dist4 = dist2; // also calls default copy const. cout << "\ndist1 = "; dist1.showdist(); // display all lengths cout << "\ndist2 = "; dist2.showdist(); cout << "\ndist3 = "; dist3.showdist(); cout << "\ndist4 = "; dist4.showdist(); cout << endl; system("PAUSE"); return 0; } 40 The Default Copy Constructor (1/2) // englret.cpp function returns value of type Distance #include <iostream> #include <stdlib.h> using namespace std; class Distance{ // English Distance class private: int feet; float inches; public: Distance() : feet(0), inches(0.0) // constructor (no args) { cout<< "No Arguments Constructor has been Called \n" ; } // constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { cout<< "Two Arguments Constructor has been Called \n" ; } void getdist(){ // get length from user cout << "Enter feet : "; cin >> feet; cout << "Enter inches: "; cin >> inches; } 41 Returning Objects from Functions (1/3) void showdist() //display distance { cout << feet << "\'-" << inches << '\"'; } Distance add_dist(Distance); // function declaration }; // add this distance to d2, return the sum Distance Distance::add_dist(Distance d2){ // function definition Distance temp; // temporary variable temp.inches = inches + d2.inches; // add the inches if(temp.inches >= 12.0){ // if total exceeds 12.0, temp.inches -= 12.0; // then decrease inches by 12.0 and temp.feet = 1; // increase feet by 1 } temp.feet += feet + d2.feet; // add the feet return temp; } 42 Returning Objects from Functions (2/3) Returning Objects from Functions  The temp object is then returned by the function using the statement return temp;  The statement in main() assigns it to dist3.  Notice that dist1 is not modified; it simply supplies data to add_dist().  Figure on next slide shows how this looks.  In the topic, “Operator Overloading”, we’ll see how to use the arithmetic + operator to achieve the even more natural expression like dist3 = dist1 + dist2; 45 temp temp.feet 22 temp.inches inches 2.25 Data in t e mp is assigned to dist using statement return temp; in add_dist() function. dist3 = distl.add_dist(dist2); 11 inches 8 inches 6.25 d2.inches Structures and Classes  In fact, you can use structures in almost exactly the same way that you use classes. The only formal difference between class and struct is that in a class the members are private by default, while in a structure they are public by default. You can just as well write class foo { int data1; public: void func(); }; //and the data1 will still be private. 47 Classes, Objects and Memory 50 data 1 data 1 data 2 data 2 data 1 data 1 data 2 data 2 data 1 data 1 data 2 data 2 Function1()Function1() Function2()Function2() Object 1 Object 2 Object 3 Static Class Data  If a data item in a class is declared as static, only one such item is created for the entire class, no matter how many objects there are.  A static data item is useful when all objects of the same class must share a common item of information.  A member variable defined as static has characteristics similar to a normal static variable: It is visible only within the class, but its lifetime is the entire program. It conti- nues to exist even if there are no objects of the class.  a normal static variable is used to retain information between calls to a function, static class member data is used to share information among the objects of a class. 51 Static Class Data  Why would you want to use static member data? As an example, suppose an object needed to know how many other objects of its class were in the program.  In a road-racing game, for example, a race car might want to know how many other cars are still in the race.  In this case a static variable Total_Cars could be included as a member of the class. All the objects would have access to this variable. It would be the same variable for all of them; they would all see the same number of Total_Cars. 52 Static Class Data  Ordinary variables are usually declared (the compiler is told about their name and type) and defined (the compiler sets aside memory to hold the variable) in the same statement. e.g. int a;  Static member data, on the other hand, requires two separate statements.  The variable’s declaration appears in the class definition,  but the variable is actually defined outside the class, in much the same way as a global variable.  If static member data were defined inside the class, it would violate the idea that a class definition is only a blueprint and does not set aside any memory. 55 //constfu.cpp demonstrates const member functions class aClass { private: int alpha; public: void nonFunc() // non-const member function { alpha = 99; // OK } void conFunc() const // const member function { alpha = 99; // ERROR: can’t modify a member } }; const Member Function  A const member function guarantees that it will never modify any of its class’s member data. 56 // const member functions & const arguments to member functions #include <iostream> using namespace std; class Distance // English Distance class { private: int feet; float inches; public: // constructor (no args) Distance() : feet(0), inches(0.0) { } // constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist(){ // get length from user cout << "\nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } 57 Distance Class and Use of const (1/3) const Member Function Arguments  if an argument is passed to an ordinary function by reference, and you don’t want the function to modify it, the argument should be made const in the function declaration (and definition). This is true of member functions as well. Distance Distance::add_dist(const Distance& d2) const{  In above line, argument to add_dist() is passed by reference, and we want to make sure that won’t modify this variable, which is dist2 in main().  Therefore we make the argument d2 to add_dist() const in both declaration and definition. 60 const Objects  In several example programs, we’ve seen that we can apply const to variables of basic types such as int to keep them from being modified.  In a similar way, we can apply const to objects of classes. When an object is declared as const, you can’t modify it.  It follows that you can use only const member functions with it, because they’re the only ones that guarantee not to modify it. e.g. A football field (for American-style football) is exactly 300 feet long. If we were to use the length of a football field in a program, it would make sense to make it const, because changing it would represent the end of the world for football fans. 61 // constObj.cpp constant Distance objects #include <iostream> using namespace std; class Distance // English Distance class { private: int feet; float inches; public: // 2-arg constructor Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() // user input; non-const function { cout << "\nEnter feet:" ; cin >> feet; cout << "Enter inches:" ; cin >> inches; } 62 const Objects (1/2)  Create a class Rectangle with attributes int length and width  Make a no argument constructor to initialize attributes to 1  Also make a two argument constructor.  Make member functions that calculate and return the perimeter and the area of the rectangle.  Also, provide void set( int l, int w) function for setting the length and width attributes.  Make a Draw function that draws a rectangle using a character * on console. ********* * * * * ********* Assignment Question No.2 65 Create a class called time  that has separate int member data for hours, minutes, and seconds.  One constructor should initialize this data to 0, and another constructor should initialize it to fixed values.  Make void print() to display time in 23:59:59 format.  Make void setTime(int,int,int) to set hour, minute, second.  include a tick() member function that increments the time stored in a Time object by one second.  Make an add member function that should add two objects of type time passed as arguments. Assignment Question No.3 66 Be sure to test the following cases: 1. Incrementing into the next minute. 2. Incrementing into the next hour. 3. Incrementing into the next day (i.e., 23:59:59 to 00:00:00). Make 1000 times loop in a main function. Call tick and print functions in that loop for an object. Also make two objects and add them to a third object and print their values. Assignment Question No.3 67 The equation of a line in standard form is ax + by = c, where both a and b cannot be zero, and a, b, and c are real numbers.  If b is not equal to zero, then –a/b is the slope of the line.  If a is equal to zero, then it is a horizontal line  if b is equal to zero, then it is a vertical line.  The slope of a vertical line is undefined.  Two lines are parallel if they have the same slope or both are vertical lines.  Two lines are perpendicular if either one of the lines is horizontal and the other is vertical or the product of their slopes is –1  Design the class lineType to store a line. To store a line, you need to store the values of a (coefficient of x), b(coefficient of y), and c. Assignment Question No.5 70  Your class must contain the following operations.  If a line is nonvertical, then determine its slope.  Determine if two lines are equal. Two lines a1x + b1y = c1 and a2x +b2y = c2 are equal if  either a1 = a2, b1 = b2, and c1= c2  or a1 = ka2, b1= kb2, and c1 = kc2 for some real number k.)  Determine if two lines are parallel.  Determine if two lines are perpendicular.  If two lines are not parallel, then find the point of intersection.  Add appropriate constructors to initialize variables of lineType.  Also write a program to test your class. Assignment Question No.5 71 Finding Point of Intersection of two lines Consider the system of linear equations ax+by=m cxtdy=n ne [2 )(5] (41 Le d y | n or AX=B where A= e 7pe=(* and B= |" | Le @ y | n or X=A™'B IAI = ad — be Adj A gt Adj A or x=TAT_ xB: “ AS TAI and IAI #0 d —b lm | -c alin} | y | = ad — be dm — bn ad — be —cm + an ad — be __an~—cm » ad —be _dm —bn *="ad —be and