Object Oriented Programming

Object Oriented Programming By Dr. Ahmad Raza Khan Index •  An overview of C++ basic concepts •  EssenDal concepts of object oriented programming including: objects, classes (data members, funcDon members. •  Constructors, Destructors •  Access and modifiers funcDons •  Friend classes and funcDons •  AbstracDon Index • 
• 
• 
• 
• 
• 
• 
inheritance base and derived classes Protected members, funcDon overriding. Public and protected and private inheritance EncapsulaDon, Reusability Virtual funcDons and polymorphism AbstracDon Operators overloading Class templates, excepDons processing. Constructor •  A class constructor is a special member funcDon of a class that is executed whenever we create new objects of that class. •  A constructor will have exact same name as the class and it does not have any return type at all not even void. It is basically used to allocate memory •  Constructors can be very useful for seMng iniDal values for certain member variables. •  Constructor is automaDcally called whenever a new object of this class is created, allowing the class to iniDalize member variables or allocate storage. •  Example a.cpp, d.cpp Destructor •  A destructor is a special member funcDon of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. It is used to delete memory allocated by the constructor. •  A destructor will have exact same name as the class prefixed with a Dlde (~) and it can neither return a value nor can it take any parameters •  Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. •  The destructor is called when the scope of the object ends or at the end of the program automaDcally. •  Example dis.cpp Access and modifiers funcDons •  Data hiding is one of the important features of Object Oriented Programming which allows prevenDng the funcDons of a program to access directly the internal representaDon of a class type. •  The access restricDon to the class members is specified by the labeled public, private, and protected secDons within the class body. The keywords public, private, and protected are called access spécifier. •  A class can have mulDple public, protected, or private labeled secDons. Access and modifiers funcDons •  Each secDon remains in effect unDl either another secDon label or the closing right brace of the class body is seen. The default access for members and classes is private. •  A protected member variable or funcDon is very similar to a private member but it provided one addiDonal benefit that they can be accessed in child classes which are called derived classes. •  Example public.cpp, priv.cpp Inheritance •  Inheritance is a form of soUware reuse in which you create a class that absorbs an exisDng class’s capabiliDes, then customizes or enhances them. •  SoUware reuse saves Dme during program development by taking advantage of proven, high-­‐quality soUware. •  When creaDng a class, instead of wriDng completely new data members and member funcDons, you can specify that the new class should inherit the members of an exisDng class •  This exisDng class is called the base class, and the new class is called the derived class. Inheritance •  Other programming languages, such as Java and C#, refer to the base class as the super-­‐ class and the derived class as the subclass. •  A derived class represents a more specialized group of objects. •  C++ offers public, protected and private inheritance. •  With public inheritance, every object of a derived class is also an object of that derived class’s base class •  However, base-­‐ class objects are not objects of their derived classes Inheritance •  For example, if we have Vehicle as a base class and Car as a derived class, then all Cars are Vehicles, but not all Vehicles are Cars—for example, a Vehicle could also be a Truck or a Boat. •  One of the most important concepts in object-­‐
oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an applicaDon. •  This also provides an opportunity to reuse the code funcDonality and fast implementaDon Dme. Inheritance •  When creaDng a class, instead of wriDng completely new data members and member funcDons, the programmer can designate that the new class should inherit the members of an exisDng class. •  This exisDng class is called the base class, and the new class is referred to as the derived class. •  The idea of inheritance implements the is a relaDonship. For example, mammal IS-­‐A animal, dog IS-­‐A mammal hence dog IS-­‐A animal as well and so on. Inheritance •  A class can be derived from more than one classes, which means it can inherit data and funcDons from mulDple base classes. •  To define a derived class, we use a class derivaDon list to specify the base class(es). A class derivaDon 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. Inheritance •  C++ has 5 types of Inheritance –  Single Inheritance –  MulDple Inheritance –  Hierarchical Inheritance –  MuDlevel Inheritance –  Hybrid Inheritance ( also known as Virtual Inheritance) Single Inheritance •  In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of inheritance. •  Example single.cpp MulDple Inheritance •  In this type of inheritance a single derived class may inherit from two or more then two base classes. •  Example mulD.cpp Hierarchical Inheritance •  In this type of inheritance, mulDple derived classes inherits from a single base class. •  Example: Her.cpp MulDlevel Inheritance •  In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class. The super class for one, is sub class for the other. •  Example : mulDlevel.cpp Hybrid (Virtual) Inheritance class A // Grandparent { .. ... }; class B : virtual public A // Parent1 { .. ... }; class C : public virtual A // Parent2 { .. ... }; class D : public B, public C // Child { .. .. }; Hybrid (Virtual) Inheritance •  Hybrid Inheritance is combinaDon of Hierarchical and MulDlevel Inheritance. •  Example : Hybrid.cpp Friend FuncDon •  A friend funcDon of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. •  Even though the prototypes for friend funcDons appear in the class definiDon, friends are not member funcDons. •  A friend can be a funcDon, funcDon template, or member funcDon, or a class or class template, in which case the enDre class and all of its members are friends. Friend FuncDon •  To declare a funcDon as a friend of a class, precede the funcDon prototype in the class definiDon with keyword friend as follows: •  E.g. friend-­‐fun.cpp , friend1.cpp AbstracDon •  Data abstracDon refers to, providing only essenDal informaDon to the outside world and hiding their background details, i.e., to represent the needed informaDon in program without presenDng the details. •  Data abstracDon is a programming (and design) technique that relies on the separaDon of interface and implementaDon. •  Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. AbstracDon •  Thus, we can say a television clearly separates its internal implementaDon from its external interface and you can play with its interfaces like the power bujon, channel changer, and volume control without having zero knowledge of its internals. •  Now, if we talk in terms of C++ Programming, C++ classes provides great level of data abstrac3on. They provide sufficient public methods to the outside world to play with the funcDonality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally. AbstracDon •  For example, your program can make a call to the sort() funcDon without knowing what algorithm the funcDon actually uses to sort the given values. In fact, the underlying implementaDon of the sorDng funcDonality could change between releases of the library, and as long as the interface stays the same, your funcDon call will sDll work. •  Access Labels Enforce Abstrac3on: •  In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels: AbstracDon •  Members defined with a public label are accessible to all parts of the program. The data-­‐abstracDon view of a type is defined by its public members. •  Members defined with a private label are not accessible to code that uses the class. The private secDons hide the implementaDon from code that uses the type. •  There are no restricDons on how oUen an access label may appear. Each access label specifies the access level of the succeeding member definiDons. The specified access level remains in effect unDl the next access label is encountered or the closing right brace of the class body is seen. AbstracDon •  Benefits of Data Abstrac3on: Data abstracDon provides two important advantages: •  Class internals are protected from inadvertent user-­‐
level errors, which might corrupt the state of the object. •  The class implementaDon may evolve over Dme in response to changing requirements or bug reports without requiring change in user-­‐level code. •  E.g. AbstracDon.cpp Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class Inheritance Base and Derived Class FuncDon Overriding •  If base class and derived class have member funcDons with same name and arguments •  If you create an object of derived class and write code to access that member funcDon then, the member funcDon in derived class is only invoked i.e. •  the member funcDon of derived class overrides the member funcDon of base class. This feature in C++ programming is known as funcDon overriding FuncDon Overriding Example : Fun-­‐Over.cpp •  Accessing the Overridden Func3on in Base Class From Derived Class •  To access the overridden funcDon of base class from derived class, scope resoluDon operator ::. For example: If you want to access get_data() funcDon of base class from derived class in above example then, the following statement is used in derived class. •  A::get_data; // Calling get_data() of class A. •  It is because, if the name of class is not specified, the compiler thinks get_data() funcDon is calling itself. FuncDon Overriding Example : Fun2.cpp Data EncapsulaDon •  All C++ programs are composed of the following two fundamental elements: •  Program statements (code): This is the part of a program that performs acDons and they are called funcDons. •  Program data: The data is the informaDon of the program which affected by the program funcDons. •  EncapsulaDon is an Object Oriented Programming concept that binds together the data and funcDons that manipulate the data, and that keeps both safe from outside interference and misuse Data EncapsulaDon •  Data encapsulaDon led to the important OOP concept of data hiding. •  Data encapsula3on is a mechanism of bundling the data, and the funcDons that use them •  data abstrac3on is a mechanism of exposing only the interfaces and hiding the implementaDon details from the user. •  C++ supports the properDes of encapsulaDon and data hiding through the creaDon of user-­‐defined types called classes Data EncapsulaDon •  We already have studied that a class can contain private, protected and public members. •  By default, all items defined in a class are private. For example: Data EncapsulaDon •  In the previous example The variables length, breadth, and height are private. •  This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulaDon is achieved. •  To make parts of a class public (i.e., accessible to other parts of your program), •  you must declare them aUer the public keyword. All variables or funcDons defined aUer the public specifier are accessible by all other funcDons in your program. Data EncapsulaDon •  Making one class a friend of another exposes the implementaDon details and reduces encapsulaDon. The ideal is to keep as many of the details of each class hidden from all other classes as possible. •  Data Encapsula3on Example: •  Any C++ program where you implement a class with public and private members is an example of data encapsulaDon and data abstracDon. Consider the following example: Data EncapsulaDon Data EncapsulaDon •  When the above code is compiled and executed, it produces the following result: Total 60 •  Above class adds numbers together, and returns the sum. •  The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class •  The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.