Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is that code reusability is hard. Object oriented programming aims to implement real world entities in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of code can access this data except that function. The main advantages and goals of OOP are to make complex software faster to develop and easier to maintain. OOP enables the easy reuse of code by applying simple and widely accepted rules (principles). Fundamental Principles of OOP In order for a programming language to be object-oriented, it enables working with classes and objects as well as the implementation and use of the fundamental object-oriented principles and concepts such as inheritance, abstraction, encapsulation and polymorphism. 1. Encapsulation Wrapping up (combing) of data and functions into a single unit is known as encapsulation. The data is not accessible to the outside world and only those functions which are wrapping in the class can access it. This insulation of the data from direct access by the program is called data hiding or information hiding. Hiding unnecessary details in our classes and providing a clear and simple interface for working with them Encapsulation. 2. Inheritance 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. Inheritance provides re usability. This means that we can add additional features to an existing class without modifying it. 3. Abstraction Data abstraction refers to, providing only needed information to the outside world and hiding implementation details. Deptt of Comp. Apps GDC Sumbal 1
O b j e c t O r i e n t e d P r o g r a m m i n g 2 It refers to dealing with objects considering their important characteristics and ignoring all other details. 4. Polymorphism Polymorphism means ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends upon the types of data used in the operation. C++ supports operator overloading and function overloading. Operator overloading is the process of making an operator to exhibit different behaviors in different instances is known as operator overloading. Function overloading is using a single function name to perform different types of tasks. Polymorphism is extensively used in implementing inheritance. Some OOP theorists also put the concept of exception handling as additional fifth fundamental principle of OOP. Class: Class is a blueprint of data and functions or methods. Class does not take any space. Syntax for class: class class_name private: //data members and member functions declarations public: //data members and member functions declarations protected: //data members and member functions declarations A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. Class is a user defined data type like structures and unions in C. Deptt of Comp. Apps GDC Sumbal 2
O b j e c t O r i e n t e d P r o g r a m m i n g 3 By default class variables are private but in case of structure it is public. In below example person is a class. Object: Objects are basic run-time entities in an object oriented system, objects are instances of a class these are defined user defined data types. Declaring object: Syntax ClassName ObjectName; Object take up space in memory and have an associated address like a structure or union in C. class person char name[20]; int id; public: void getdetails() int main() person p1; //p1 is a object When a program is executed the objects interact by sending messages to one another. Each object contains data and code to manipulate the data. Objects can interact without having to know details of each others data or code, it is sufficient to know the type of message accepted and type of response returned by the objects. Deptt of Comp. Apps GDC Sumbal 3
O b j e c t O r i e n t e d P r o g r a m m i n g 4 Accessing data members and member functions: The data members and member functions of class can be accessed using the direct member access operator or dot(. ) operator with the object. For example if the name of object is obj and you want to access the member function with the name printname() then you will have to write obj.printname(). This access control is given by Access modifiers in C++. There are three access modifiers : public, private and protected. // C++ program to demonstrate accessing of data members #include <iostream.h> using namespace std; class example // Access specifier public: // Data Members int id; // Member Functions() void printid() cout << "My ID is: " << id; int main() // Declare an object of class example example obj1; // accessing data member obj1.id = 123; // accessing member function obj1.printid(); return 0; Deptt of Comp. Apps GDC Sumbal 4
O b j e c t O r i e n t e d P r o g r a m m i n g 5 ------------------------------------------------------------------------------------------------ // C++ program to demonstrate function declaration outside class #include <iostream.h> using namespace std; class example public: int id; // printid is not defined inside class definition void printid(); // Definition of printid using scope resolution operator :: void example::printid() cout << "Identity No. is: " << id; int main() example obj1; obj1.id=15; // call printid () obj1.printid(); return 0; ---------------------------------------------------------------------------------------------------- Constructors Constructors are special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition. Deptt of Comp. Apps GDC Sumbal 5
O b j e c t O r i e n t e d P r o g r a m m i n g 6 A class constructor does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables. There are 3 types of constructors: 1. Default constructors 2. Parametrized constructors 3. Copy constructors (#Definitions on note-book) // C++ program to demonstrate DEFAULT AND PARAMETRIZED constructors #include <include.h> using namespace std; class example public: int id; //Default Constructor example() cout << "Default Constructor called" << endl; id=-1; //Parametrized Constructor example (int x) cout << "Parametrized Constructor called" << endl; id=x; int main() // obj1 will call Default Constructor example obj1; cout << Id is: " <<obj1.id << endl; Deptt of Comp. Apps GDC Sumbal 6
O b j e c t O r i e n t e d P r o g r a m m i n g 7 // obj1 will call Parametrized Constructor example obj2(21); cout << "Id is: " <<obj2.id << endl; return 0; Copy Constructor A Copy Constructor creates a new object, which is exact copy of the existing copy. The compiler provides a default Copy Constructor to all the classes. (# Rest on note-book including passing objects as parameters) Function and Operator Overloading C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. The process of selecting the most appropriate overloaded function or operator is called overload resolution. Function overloading reduces the investment of different function names and used to perform similar functionality by more than one function. (#on note-book) Deptt of Comp. Apps GDC Sumbal 7
O b j e c t O r i e n t e d P r o g r a m m i n g 8 Function Overloading Deptt of Comp. Apps GDC Sumbal 8
O b j e c t O r i e n t e d P r o g r a m m i n g 9 Function Overloading Example Deptt of Comp. Apps GDC Sumbal 9
O b j e c t O r i e n t e d P r o g r a m m i n g 10 Operator Overloading Deptt of Comp. Apps GDC Sumbal 10
O b j e c t O r i e n t e d P r o g r a m m i n g 11 Unary Operator ++ Pre and Post Overload Deptt of Comp. Apps GDC Sumbal 11
O b j e c t O r i e n t e d P r o g r a m m i n g 12 Constructor Overloading in C++ In C++, we can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading. Overloaded constructors essentially have the same name (name of the class) and different number of arguments. A constructor is called depending upon the number and type of arguments passed. While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. // C++ program to illustrate Constructor overloading #include <iostream> using namespace std; class construct public: float area; // Constructor with no parameters construct() area = 0; // Constructor with two parameters construct(int a, int b) area = a * b; void disp() cout<< area<< endl; int main() Deptt of Comp. Apps GDC Sumbal 12
O b j e c t O r i e n t e d P r o g r a m m i n g 13 // Constructor Overloading with two different constructors of class name construct obj1; construct obj2( 10, 20); obj1.disp(); obj2.disp(); return 0; Polymorphism The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same time is a father, an employee. So a same person can have different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming. In C++ polymorphism is mainly divided into two types: Compile time Polymorphism Runtime Polymorphism 1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. (Already done) 2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding. o Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. Deptt of Comp. Apps GDC Sumbal 13
O b j e c t O r i e n t e d P r o g r a m m i n g 14 Virtual Function Deptt of Comp. Apps GDC Sumbal 14
O b j e c t O r i e n t e d P r o g r a m m i n g 15 Why Virtual Function? Deptt of Comp. Apps GDC Sumbal 15
O b j e c t O r i e n t e d P r o g r a m m i n g 16 Programming Example Deptt of Comp. Apps GDC Sumbal 16
O b j e c t O r i e n t e d P r o g r a m m i n g 17 Pure Virtual Functions It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. Deptt of Comp. Apps GDC Sumbal 17
O b j e c t O r i e n t e d P r o g r a m m i n g 18 Deptt of Comp. Apps GDC Sumbal 18
O b j e c t O r i e n t e d P r o g r a m m i n g 19 Deptt of Comp. Apps GDC Sumbal 19
O b j e c t O r i e n t e d P r o g r a m m i n g 20 Inheritance Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. Sub Class: The class that inherits properties from another class is called Sub class or derived class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class The idea of inheritance implements the is a relationship. To define a derived class, we use a class derivation list to specify the base class. A class derivation list names one or more base classes and has the form class derived-class: access-specifier base-class Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default. We can summarize the different access types according to - who can access them in the following way Access public protected private Same class yes yes yes Derived classes yes yes no Outside classes yes no no Deptt of Comp. Apps GDC Sumbal 20
O b j e c t O r i e n t e d P r o g r a m m i n g 21 Type of Inheritance Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only. Syntax: class subclass_name : access_mode base_class //body of subclass // C++ program to explain Single inheritance #include <iostream> using namespace std; // base class class Vehicle public: void func() cout << "This is a Vehicle" << endl; // sub class derived from two base classes class Car: public Vehicle // main function Deptt of Comp. Apps GDC Sumbal 21
int main() // creating object of sub class will // invoke the member function of base classes Car obj; obj.func(); return 0; 1. Output: This is a vehicle O b j e c t O r i e n t e d P r o g r a m m i n g 22 2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes. Syntax: class subclass_name : access_mode base_class1, access_mode base_class2,... //body of subclass Here, the number of base classes will be separated by a comma (, ) and access mode for every base class must be specified. // C++ program to explain multiple inheritance #include <iostream> using namespace std; // first base class Deptt of Comp. Apps GDC Sumbal 22
class Vehicle public: Vehicle() cout << "This is a Vehicle" << endl; // second base class class FourWheeler public: FourWheeler() cout << "This is a 4 wheeler Vehicle" << endl; // sub class derived from two base classes class Car: public Vehicle, public FourWheeler // main function int main() // creating object of sub class will // invoke the constructor of base classes Car obj; return 0; Output: This is a Vehicle O b j e c t O r i e n t e d P r o g r a m m i n g 23 Deptt of Comp. Apps GDC Sumbal 23
O b j e c t O r i e n t e d P r o g r a m m i n g 24 This is a 4 wheeler Vehicle Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class. // C++ program to implement Multilevel Inheritance #include <iostream> using namespace std; // base class class Vehicle public: Vehicle() cout << "This is a Vehicle" << endl; class fourwheeler: public Vehicle public: fourwheeler() cout<<"objects with 4 wheels are vehicles"<<endl; Deptt of Comp. Apps GDC Sumbal 24
// sub class derived from two base classes class Car: public fourwheeler public: car() cout<<"car has 4 Wheels"<<endl; // main function int main() //creating object of sub class will //invoke the constructor of base classes Car obj; return 0; Output: This is a Vehicle Objects with 4 wheels are vehicles Car has 4 Wheels O b j e c t O r i e n t e d P r o g r a m m i n g 25 Deptt of Comp. Apps GDC Sumbal 25
O b j e c t O r i e n t e d P r o g r a m m i n g 26 Exception Handling in C++ One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch,and throw. throw A program throws an exception when a problem shows up. This is done using a throw keyword. catch A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows try // protected code catch( ExceptionName e1 ) // catch block catch( ExceptionName e2 ) // catch block catch( ExceptionName en ) // catch block Deptt of Comp. Apps GDC Sumbal 26
O b j e c t O r i e n t e d P r o g r a m m i n g 27 Program to demonstrate Exception Handling in C++ (Multiple Catch Statements) #include <iostream.h> using namespace std; int main() int x = -1; // Some code cout << "Before try \n"; try cout << "Inside try \n"; if (x < 0) throw x; cout << "After throw (Never executed) \n"; Else Throw E ; catch (int x) cout << "Exception Caught \n"; catch (char x ) cout << "Exception Caught \n"; cout << "After catch (Will be executed) \n"; return 0; Deptt of Comp. Apps GDC Sumbal 27
O b j e c t O r i e n t e d P r o g r a m m i n g 28 Output: Before try Inside try Exception Caught After catch (Will be executed) Second Example of Exception Handling (Division by Zero ) #include <iostream.h> using namespace std; double division(int a, int b) if( b == 0 ) throw b; return (a/b); int main () int x = 50; int y = 0; double z = 0; try z = division(x, y); cout << z << endl; catch (int a) cout << Exception Caught Division by Zero << endl; return 0; Deptt of Comp. Apps GDC Sumbal 28
O b j e c t O r i e n t e d P r o g r a m m i n g 29 Deptt of Comp. Apps GDC Sumbal 29