C++ largest no between three nos

385 views

Published on

c++

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
385
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C++ largest no between three nos

  1. 1. Data Structures using OOP C++ Lecture 1References: 1. E Balagurusamy ,”Object Oriented Programming with C++”, 4th edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, “Data Structures and Program Design in C++”, Prentice-Hall 2000.IntroductionThere are two weaknesses related with structured programming. Firstly,functions have unrestricted access to global data. This causes a program’sstructure difficult to conceptualize. In addition, it makes the programdifficult to modify. Any change made in a global data item maynecessitate rewriting all the functions that access that item. Secondly, thearrangement of separate data and functions does a poor job of modelingthings in the real world. In the real world we deal with objects such aspeople and cars. Such objects aren’t like data and they aren’t likefunctions. Complex real-world objects have both data and functions.Therefore there was a need for a new programming approach which iscalled Object-Oriented Programming.Object-Oriented Programming (OOP) • OOP incorporates the best features of structured programming with several powerful new concepts. • It provides a new way of thinking, organizing and developing programs. • OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. • OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. The data ofAss. Lec. Zainab Mahmood Fadhil Page 1
  2. 2. Data Structures using OOP C++ Lecture 1 an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects.Fundamental OOP ConceptsThe principles of OOP include: • Class: is like a blueprint (general form) used to create objects. A class also is an abstract data type that can be treated like any other built-in data type. A class defines the attributes of its objects and the methods that can be applied to its objects. • Object: is the basic run-time entity in an object-oriented system. It may represent a person, a place, a bank account, etc. An object is also called an instance of a class. • Encapsulation: is the mechanism that binds together data and functions into a single unit (called class). The data is not accessible to the outside world, and only the functions which are wrapped in the class can access it. This insulation of data from direct access is called data hiding or information hiding. • Inheritance: is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. It also provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. • Polymorphism: is the ability for objects of different classes related by inheritance to respond differently to the same message. The same message sent to many different types of objects takes on “many forms”--hence the term polymorphism.Ass. Lec. Zainab Mahmood Fadhil Page 2
  3. 3. Data Structures using OOP C++ Lecture 1ClassesThe general form of a class declaration in C++ is: class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; };- The keyword class indicates that an abstract data type called class_name will be specified.- The class body is enclosed within braces and terminated by a semicolon.- The variables declared inside the class are known as data members and the functions are known as member functions.- These functions and variables are usually grouped under two sections: namely, private and public.- Only the member functions can have access to the private data members and private functions. However, the public members can be accessed from outside the class.- Note that declaring data variables as public defeat the idea of data hiding and therefore should be avoided.Ass. Lec. Zainab Mahmood Fadhil Page 3
  4. 4. Data Structures using OOP C++ Lecture 1A Simple Class Example class item { private: int number; float cost; public: void getdata(int a, float b); void putdata(); };Here, we have defined a class called item. This name is used to declareobjects of that class. The data members (number and cost) are declaredas private, while the member functions (getdata() and putdata())are declared as public. As mentioned earlier, these two functions providethe only access to the two data members from outside the class. Note that,at this stage class definition does not allocate any memory space.ObjectsOnce a class has been defined, we can create objects of that type asfollows: item x;This statement creates an object x of type item. At this stage, memoryspace is allocated to the object x. We may also declare more than oneobject in one statement, for example item x, y, z;Another way to create objects is by placing their names immediately afterthe closing brace in the class definition, for example:Ass. Lec. Zainab Mahmood Fadhil Page 4
  5. 5. Data Structures using OOP C++ Lecture 1 class item { ……… ……… } x, y, z;Accessing Class MembersAs previously mentioned, the public member functions can be accessedonly from outside the class. This can be done using the dot operator, forexample x.getdata(100, 75.5);This function call statement is valid and assigns the value 100 to numberand 75.5 to cost of the object x by implementing the getdata()function.Similarly, the statement x.putdata();would display the values of number and cost.While the statement x.number =100;is illegal because number is a private member and cannot be accessedfrom outside the class.When a variable is declared as public, it can be accessed by the objectsdirectly, for example:Ass. Lec. Zainab Mahmood Fadhil Page 5
  6. 6. Data Structures using OOP C++ Lecture 1 class xyz { private: int x; int y; public: int z; }; ………… ………… xyz p; // create object p p.x = 0; // error, x is private p.z = 10; // OK, z is public ………… …………However, the public declaration of data conflicts with the OOP conceptdata hiding and therefore should be avoided.Definition of Member FunctionsClass member functions can be defined in two places:Outside the Class DefinitionExample: void item :: getdata(int a, float b) { number = a; cost = b; }Here, the membership label item :: tells the compiler that the functiongetdata() belongs to the class item. That is, the scope of the functiongetdata() is restricted to the class item specified in the header line.The symbol :: is called the scope resolution operator. Note thestatements number = a; cost = b;Ass. Lec. Zainab Mahmood Fadhil Page 6
  7. 7. Data Structures using OOP C++ Lecture 1show that the member functions can have direct access to private dataitems. Similarly, the function putdata() is defined outside the classitem as follows: void item :: putdata() { cout << ”Number :” << number << “n” ; cout << ”Cost :” << cost << “n” ; }Inside the Class DefinitionExample: class item { private: int number; float cost; public: void getdata(int a, float b); void putdata() { cout << ”Number :” << number << “n” ; cout << ”Cost :” << cost << “n” ; } };Note: Normally, only small functions are defined inside the classdefinition.A Complete C++ Program with ClassThe following program includes all the details discussed so far:#include <iostream>using namespace std;class item { private: int number; float cost;Ass. Lec. Zainab Mahmood Fadhil Page 7
  8. 8. Data Structures using OOP C++ Lecture 1 public: void getdata(int a, float b); void putdata() { cout << “number :” << number << “n”; cout << “cost :” << cost << “n”; } };void item :: getdata(int a, float b){ number = a; cost = b;}void main(){ item x; //create object x cout << “nObject x “ << “n; x.getdata(100, 299.95); x.putdata(); item y; //create another object y cout << “nObject y “ << “n; x.getdata(200, 175. 50); x.putdata();}The output of the above program is:Object xnumber :100cost :299.95Object ynumber :200cost :175.5Ass. Lec. Zainab Mahmood Fadhil Page 8
  9. 9. Data Structures using OOP C++ Lecture 1Nesting of Member FunctionsWe have shown that a class member function can be called only by anobject of that class using a dot operator. However, a member function canbe called inside another member function of the same class. This is callednesting of member functions.Example:#include <iostream>using namespace std;class set{ private: int m, n; public: void input(); void display(); int largest();};int set :: largest(){ if(m >= n) return m; else return n;}void set :: input(){ cout << “Input values of m and n” << “n”; cin >> m >> n;}void set :: display(){ cout << “Largest value = ” << largest() << “n”; //calling member function}void main(){Ass. Lec. Zainab Mahmood Fadhil Page 9
  10. 10. Data Structures using OOP C++ Lecture 1 set A; A.input(); A.display();}The output of the above program would be:Input values of m and n25 18Largest value = 25Private Member FunctionsSome tasks such as deleting a customer account, or providing anincrement to an employee may require certain functions to be hidden (likeprivate data) from the outside calls. We can place these functions in theprivate section. Note that a private member function can only be called byanother member function of its class, and cannot be called by an object.Example:class sample{ private: int m; void read(); // private member function public: void update(); void write();};……………………sample s1;s1.read(); // won’t work; objects cannot access // private members from outside the class……………………The function call statement s1.read();Ass. Lec. Zainab Mahmood Fadhil Page 10
  11. 11. Data Structures using OOP C++ Lecture 1is illegal. Instead, the function read() can be called by the functionupdate() to update the value of m.void sample :: update(){ read(); // simple call; no object used}ConstructorsA constructor is a member function whose name is the same as the classname. The constructor is used to initialize the objects of its class, i.e. itconstructs the values of data members of the class. The constructor isautomatically invoked whenever object of its associated class is created.Example: #include <iostream> using namespace std; class integer { private: int m, n; public: integer(); // constructor declaration void printdata(); }; integer :: integer() // constructor definition { m = 0; n = 0; } void integer :: printdata() { cout << “ m = “ << m << “n” << “n = “ << n << “n”; } void main() {Ass. Lec. Zainab Mahmood Fadhil Page 11
  12. 12. Data Structures using OOP C++ Lecture 1 integer intl; intl.printdata(); }The declaration statement integer intl;not only creates the object intl of type integer but alsoautomatically initializes its data members m and n to zero.The output of the above program ism=0n=0Notes • The constructor should be declared in the public section. • The constructor does not have return type, (not even void), and therefore it cannot return any value. • There is no need to write any statement to invoke the constructor function because it is invoked automatically when the object is created. • A constructor that accepts no arguments is called the default constructor. • If no constructor is defined, then the compiler creates an implicit constructor. • The constructor can take arguments like other C++ functions. This is called parameterized constructor.Parameterized ConstructorsSometimes we need to initialize the data elements of different objectswith different values when they are created. This can be done by passingAss. Lec. Zainab Mahmood Fadhil Page 12
  13. 13. Data Structures using OOP C++ Lecture 1arguments to the constructor function when objects are created. Suchconstructor is called parameterized constructor.Example:#include <iostream>using namespace std;class integer{ private: int m, n; public: integer(int , int ); //parameterized constructor void printdata();};integer :: integer(int x, int y){ m = x; n = y; }void integer :: printdata(){cout << ”m = ” << m << “n” <<”n = ” << n << “n“;}void main(){integer intl(1, 100);intl.printdata();}The output of the above program ism=1n = 100Note that when we use parameterized constructor, we must pass the initialvalues as arguments to the constructor function when an object isdeclared. For example, in the above program, the following declarationstatement integer intl;may not work. In this case we need to define multiple constructors as inthe following example:Ass. Lec. Zainab Mahmood Fadhil Page 13
  14. 14. Data Structures using OOP C++ Lecture 1#include <iostream>using namespace std;class integer{ private: int m, n; public: integer(); integer(int , int ); //parameterized constructor void printdata();};integer :: integer() { m = 0; n = 0; }integer :: integer(int x, int y){ m = x; n = y; }void integer :: printdata(){cout << ”m = ” << m << “n” <<”n = ” << n << “n“;}void main(){integer intl1, intl2(1, 100);cout<<”OBJECT 1 n”;intl1.printdata();cout<<”OBJECT 2 n”;intl2.printdata();}The output of the above program isOBJECT 1m=0n=0OBJECT 2m=1n = 100Note: When more than one constructor function is defined in a class, wesay that constructor overloading.Ass. Lec. Zainab Mahmood Fadhil Page 14
  15. 15. Data Structures using OOP C++ Lecture 1DestructorsA destructor is a member function whose name is the same as the classname but is preceded by a tilde ~ . The destructor is used to destroy theobjects that have been created by a constructor. For example, thedestructor for the class integer is defined as follows: ~integer() { }Notes• A destructor never takes any arguments nor does it return any value.• A destructor will be invoked implicitly by the compiler upon exit from the program (or block or function) to free memory space.Example:#include <iostream>using namespace std;int count = 0;class alpha{public : alpha () { count++; cout << “nObject#“ << count << “ is created ”; } ~alpha() { cout << “nObject#” << count << “ is destroyed ”; count--; }};void main(){ cout << “nnENTER MAINn”; alpha A1, A2, A3, A4;Ass. Lec. Zainab Mahmood Fadhil Page 15
  16. 16. Data Structures using OOP C++ Lecture 1 { cout << “nnENTER BLOCKn”; alpha A5; alpha A6; } cout << “nnRE-ENTER MAIN THEN EXIT PROGRAM”;}The output of the above program is:ENTER MAINObject#1 is createdObject#2 is createdObject#3 is createdObject#4 is createdENTER BLOCKObject#5 is createdObject#6 is createdObject#6 is destroyedObject#5 is destroyedRE-ENTER MAIN THEN EXIT PROGRAMObject#4 is destroyedObject#3 is destroyedObject#2 is destroyedObject#1 is destroyedNote that the objects are destroyed in the reverse order of creation.Ass. Lec. Zainab Mahmood Fadhil Page 16

×