Oops concepts • • • • • • • • Object-orientation Objects and classes Overloading Inheritance Polymorphism Generic Programming Exception Handling Introduction to design patterns Learning Objectives • • • • • • Structure Definition Classes vs. Objects Interface and Implementation Constructors and Destructors Set and get Functions Constant Objects and constant Member structure • Structure is a convenient tool for handling a group of logically related data items array: collection of values of same type Structure: collection of values of different types • It is a user-defined data type with a template that serves to define its data properties. • Example: • Struct student { char name[20]; int roll_number; float total_marks; }; The keyword Struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. Conti… •Definition: struct Student Name of new struct "type" { char name[10]; member names int id; int secno; }; Limitations of structure • We cannot process two complex numbers to any other specification Example: C3= C1 + C2 Structures do not permit data hiding. Example: • C=1.233 • Dot Operator (.) to access members – s1.name – s1.id – s1.secno Class vs Object • “Class “ refers to a blueprint . It defines the variables and methods the objects support. It is the basic unit of encapsulation. It also defines as the collection of a similar types of objects. • “Object” is an instance(properties) of a class. Each object has a class which defines its data and behaviour. Cont.. • Software objects model real-world objects or abstract concepts E.g. dog, bicycle, queue Real-world objects have states and behaviors Dogs' states: name, color, breed, hungry Dogs' behaviour: barking, fetching, sleeping Example • A class is like a blueprint. Out of a blueprint, a builder can build a house. • One class can be reused many times to make many objects of the same class • Struct Time { int hour; int minute; int second; }; Class Time can be used to create many Time objects Like wakeup time, breakfast time, lunch time, dinner time, bed time, …. Cont… • • • • • • Class is a tool to realize objects Class is a tool for defining a new type Example: Lion is an object Student is an object Both has some attributes and some behaviors Classes • Similar to structures – Adds member FUNCTIONS – Not just member data • Integral to object-oriented programming – Focus on objects • Object: Contains data and operations • In C++, variables of class type are objects Class Definitions: • Defined similar to structures • Example: class Rectangle name of new class type { public: int width; member data int height; void set_values(); member function! }; • Notice only member function’s prototype – Function’s implementation is elsewhere Class Example Why Member Function • The Function components of a class are called a member function • They model the behaviour of an object • Objects can make their data invisible • Object remains in consistent state • Classes that can be used to instantiate objects are called concrete classes. Example • Class person • { Char name[30]; Int age; Public: void getdata(void); void display (void); } //New data type Example • • Void person :: getdata(void) //member function { cout<< “ Enter name: “ ; cin >> name; cout << “Enter age: “ ; cin >> age; } Void person :: displayl (void) //member function { cout << “\n Name: “ << name; cout << “\n Age: “ << age ; } Main() { person p; //object of type person p.getdata() ; p.display(); } Output Enter name: xxxx Enter age : 18 Name:xxxx Age:18 Class Member Access • Members accessed same as structures • Example: rect.width; rect.height; – And to access member function: rect.set_values(); Invokes member function Class Member Functions • Must define or "implement" class member functions • Like other function definitions – Can be after main() definition – Must specify class: void Rectangle::set_values() {…} • :: is scope resolution operator • Instructs compiler "what class" member is from • Item before :: called type qualifier Class Member Functions Definition • Notice output() member function’s definition (in next example) • Refers to member data of class – No qualifiers • Function used for all objects of the class – Will refer to "that object’s" data when invoked – Example: today.output(); • Displays "today" object’s data 6-17 #include <iostream> using namespace std; class Rectangle { int width, height; public: void set_values (int,int); int area() {return width*height;} }; void Rectangle::set_values (int x, int y) { width = x; height = y; } int main () { Rectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } 6-18 Interface and Implementation • • • • • • • • • • • • • • • An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data. A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows: class Box { public: // pure virtual function virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; A request for an object to perform one of its operations (methods) All communication between objects is done via messages Interfaces Messages define the interface to the object Everything an object can do is represented by its message interface The interfaces provide abstractions You shouldn't have to know anything about what is in the implementation in order to use it (black box) An interface is a set of operations (methods) that given object can perform Interface and Implementation • public: The member (data or function) is accessible and available to all in the system. • private: The member (data or function) is accessible and available within this class only. • Instead of putting all the codes in a single file. We shall "separate the interface and implementation" by placing the codes in 3 files. • Circle.h: defines the public interface of the Circle class. • Circle.cpp: provides the implementation of the Circle class. • TestCircle.cpp: A test driver program for the Circle class. Public and Private Members • Data in class almost always designated private in definition! – Upholds principles of OOP – Hide data from user – Allow manipulation only via operations • Which are member functions • Public items (usually member functions) are "user-accessible“ • Example : Modify previous example: class Rectangle { public: void setvalues(); private: int width, height; }; • Data now private ,Objects have no direct access • Declare object: Rectangle rect; Object rect can ONLY access public members – cin >> rect.width; cout << rect.height; // NOT ALLOWED! – Must instead call public operations: • rect.setvalues(); Cont… • • • • • • • • • • • • • • • • • • #include <iostream> using namespace std; // Base class class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: I nt width; I nt height; }; Cont… • • • • • • • • • // Derived classes class Rectangle: public Shape { public: int getArea() { return (width * height); } }; Con… • • • • • • • • • • • • • • • • • • • • • • class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; } When the above code is compiled and executed, it produces the following result: Total Rectangle area: 35 Total Triangle area: 17 Cont… • • • • Circle.h-Header /* The Circle class Header (Circle.h) */ #include <string> // using string using namespace std; • • • • • • // Circle class declaration class Circle { private: // Accessible by members of this class only // private data members (variables) double radius; string color; cont.. • public: // Accessible by ALL • // Declare prototype of member functions • // Constructor with default values • Circle(double radius = 1.0, string color = "red"); • • • • • // Public getters & setters for private data members double getRadius() const; void setRadius(double radius); string getColor() const; void setColor(string color); • // Public member Function • double getArea() const; • }; Constructors and Destructors Cont.. Destructors • As the name Implies, is used to destroy the objects that have been created by a constructor. • The destructor is a member function whose name is the same as the class name but is preceded by a tilde(~). • Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. Example • Matrix:: ~matrix () { for (int = 0; i< d1; i++) delete p[i]; delete p; } Cont… Example: ~stack() { delete []a; cout<<"\n Destructing the stack"; } Functions • Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: type name ( parameter1, parameter2, ...) { statements } Where: - type is the type of the value returned by the function. - name is the identifier by which the function can be called. - parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from. - statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does. Cont… • • • • • • • • • • • • • • // function example #include <iostream> using namespace std; int addition (int a, int b) { int r; r=a+b; return r; } int main () { int z; z = addition (5,3); cout << "The result is " << z; } Set and get functions • Classes often provide public member functions to allow clients of the class to set ( write) or get (read) the values of private datamembers. • Specifically a member function that sets data member InteresRate might be named setInterestRate and a member function that gets the InterestRate might be named getInterestRate. Get functions are also commonly called “query” functions. Example • • • • • • • • • // set functions setTime (int, int, int); // set hour,minute,second setHour (int); //set hour setMinute(int);//set minute set second (int);//set second // get functions Int getHour () ; // return hour Int getMinute(); // return minute Int getSecond(); // return second Constant Objects and Constant Member • Protect argument – Use constant parameter • Also called constant call-by-reference parameter – Place keyword const before type – Makes parameter "read-only" – Attempt to modify parameter results in compiler error • Some objects need to be modifiable and some do not modify const Time noon (12, 0, 0); Declares a const object noon of class Time and initializes it to 12 noon. • A const object cannot be modified by assignment so it must be initialized. • When a data member of a class is declared const, a member initializer must be used to provide the constructor with the initial value of the data member for an object of the class. Cont… • If a member function does not alter any data in the class, then may declare it as a const member function void mul(int,int) const; double get balane() const; • The qualifier const is appended to the fuction prototypes(in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values. Cont… • Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in firstout), where elements are inserted and extracted only from one end of the container. • Create a class to implement the data structure STACK. 1. Write a constructor to initilize the Top of the STACK to 0. write a Member function PUSH(), To insert and element and member function POP() . To delete an element check for overflow and under flow condition. • Example Write a program to implement the data structure STACK as class and write a constructor to initialize the TOP of the STACK to 0. Write a member function PUSH () to insert an element and member function POP () to delete an element and LIST () to display all elements in the STACK. Check for overflow and under flow condition. #include<iostream> using namespace std; class STACK { int tos,* a, max; public: STACK( int s) { tos=0; max=s; a=new int[s]; } ~ STACK ( ) { delete [ ]a; cout << "\n Destructing the stack"; } void PUSH(int); void POP(); void VIEW(); }; void STACK :: PUSH( int item) { if(tos ==max-1) cout<<"The stack is full \n "; else { tos ++; a[tos]=item; cout<<"\n"<<item<<" Inserted into stack"; } return ; } void STACK :: POP( ) { int i; if (tos==0) { cout<<"stack is empty"; return (0); } else { i=a[tos]; tos --; return(i); } } void STACK :: VIEW() { int i ; if (tos==0) cout<<"stack is empty\n"; else { cout<<" The elements of stack are"<<"\n"; for (i=tos; i>=1; i--) cout<<"\n"<<a[i]; } } int main() { int s,n,c, item; cout<<"\n Enter the Size of stack:"; cin>>s; stack st(s); STACK st(s); do { cout<<"\n 1.Push\n 2.Pop\n 3.View\n 4.Exit"; cin>>c; switch(c) { case 1: cout<<"\n Enter the element to be pushed:"; cin>>n; st.PUSH(n); break; case 2: item=st.POP(); if(item==0) cout<<"\n UNDERFLOW"; else cout<<"\n"<<item<<" has been removed from stack"; break; case 3: st.VIEW(); break; case 4: cout<<"\nExit"; break; default: cout<<"\n Enter the correct choice:"; break; } }while(c!=4); }