OOCP Unit-2 to 4 PDF

Summary

This document includes lecture notes on various topics in object-oriented programming (OOP), specifically in C++. The topics discussed include data members, mutable data members, static data members, member functions (including nested, overloaded, constant, member functions with default arguments, inline, static), and different types of inheritance like single, multilevel, multiple, hierarchical, hybrid. The different types of memory management and virtual functions are also covered.

Full Transcript

TOPICS Different types of Data members Nithya, St. Xavier’s College (Autonomous) TYPES OF DATA MEMBERS 1. Constant data members 2. Mutable data members 3. Static data members Nithya, St. Xavier’s College (Autonomous) CONSTANT DATA MEMBERS The data members who...

TOPICS Different types of Data members Nithya, St. Xavier’s College (Autonomous) TYPES OF DATA MEMBERS 1. Constant data members 2. Mutable data members 3. Static data members Nithya, St. Xavier’s College (Autonomous) CONSTANT DATA MEMBERS The data members whose value cannot be changed throughout the execution of the program is known as constant data members. The constant data members are declared by preceding the qualifier const as shown below: const int x = 6; Any attempt to change the value of x will generate an error. The memory allocated for Constant data member is read only memory. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) MUTABLE DATA MEMBERS Whenever a member function is made constant, as studied earlier, using the const qualifier as the suffix to its function definition header and to its function prototype, then, the function cannot modify the data member of its class. But, if the need arises, such that, the constant member functions has to modify the value of the data member, then the data member has to be declared by prefixing the keyword 'mutable’ Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) STATIC DATA MEMBERS Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) TOPICS Different types of Member Functions Nithya, St. Xavier’s College (Autonomous) TYPES OF MEMBER FUNCTIONS 1. Nested Member Function 2. Overloaded Member Function 3. Constant Member Function 4. Member Function with Default Arguments 5. Inline Member Function 6. Static Member Function Nithya, St. Xavier’s College (Autonomous) 1. NESTED MEMBER FUNCTION A member function of a class can be called only by an object of that class using a dot operator. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) 2. OVERLOADED MEMBER FUNCTION Member functions within the same class can be overloaded. Remember that a function is called based on its signature, which is the list of argument types in its parameter list. You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Nithya, St. Xavier’s College (Autonomous) Two Scenarios: a) Overloaded Member Function within the same class b) Overloaded Member Functions among two different classes Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) 3. CONSTANT MEMBER FUNCTION The constant member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A constant member function can be called by any type of object. Non-const functions can be called by non-const objects only. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) 4. MEMBER FUNCTION WITH DEFAULT ARGUMENTS In C++, the member functions of a class assigns default values for some or all of the formal arguments which does not have a corresponding matching actual arguments in the function calls and those default values are known as default arguments to member functions. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) 5. INLINE MEMBER FUNCTION An inline member function is a function that is expanded inline with the main program at the point of invocation when it is invoked. This is something very similar to using a macro. To cause a compiler to replace the member function call with its corresponding function code rather than calling the function definition( i.e., to make a function definition inline with the function call ), the function definition has to be preceded with the keyword 'inline. Nithya, St. Xavier’s College (Autonomous) There are two ways by which member functions can be made inline. They are:  Defining the member function outside the class and prototyping the member function within the class.  Automatic inline function Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) 6. STATIC MEMBER FUNCTION By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) TOPICS Friend Functions Nithya, St. Xavier’s College(Autonomous) FRIEND FUNCTION A non-member function of a class cannot have access to the private data of that class. But sometimes if such a need arises, where in, the private data members of a class should be accessed by non-member functions, C++ allows the non-member function to be made as a friend of that class. Now the non-member function, which is declared as a friend of a particular class, can have access to the private data members of that class to which it has been declared as a friend. To make an outside function friendly to the class, we have to declare the non- member function as a friend of the class by preceding the 'friend' keyword before the function prototype inside the class Nithya, St. Xavier’s College(Autonomous) SYNTAX friend () where,  Friend = a keyword to make a function friend to a class  data type = return type of the friend function  FunctionName = name of the friend function Nithya, St. Xavier’s College(Autonomous) TYPES OF FRIEND FUNCTIONS 1. Friend Non-Member Function 2. Friend Member Function 3. Friend to more than one class Nithya, St. Xavier’s College(Autonomous) FRIEND NON-MEMBER FUNCTION When an outside function, which does not belong to any of the other class, in other words, which is not a member any other class, is made as friend of a particular class, it is known as friend non-member functions. Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) FRIEND MEMBER FUNCTION If a member function of class say, 'dimple' wants to access the private data members of another class say 'simple', then the member function of class 'dimple has to be declared as the friend of the class 'simple' within the class simple' declaration. This type of friend functions are known as friend member functions. Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) FRIEND TO MORE THAN ONE CLASS An independent function belonging to none of the class can be declared as the friend of more than one class. Here, the friend function can access the private data members of all the class, to which it is declared as a friend. Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) CHARACTERISTICS OF FRIEND FUNCTIONS The friend function can be invoked without the help of any object. The friend function is not in the scope of the class to which the function has been declared as friend. The friend functions usually have objects as their arguments. The friend function can be declared either in the private or public section of the class. Nithya, St. Xavier’s College(Autonomous) The friend function has to be preceded by the keyword friend. Unlike member functions, the friend function cannot access the member names directly. The data members of the class has to be accessed using an object name and object to member access operator( dot operator () ). Nithya, St. Xavier’s College(Autonomous) Nithya, St. Xavier’s College(Autonomous) TOPICS Friend Class Array of Class objects Passing Class objects to functions Returning objects from functions Nithya, St. Xavier’s College (Autonomous) FRIEND CLASS A class can be made as a friend of another class. If, a class Y is a friend of class X, then, all the member functions of class Y can access the private members of class X. But the member functions of class X is restricted in accessing the private members of the class "Y. To declare class Y as a friend of class X, then the following statement has to be included in either the private or public section of class X  friend class Y; Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) ARRAY OF CLASS OBJECTS The declaration of array of objects is very much similar to declaration of array of structures. As an array can be of any data type, we can have arrays of variables that are of the class type. Such variables are called as Array of objects". Array of objects are greatly used while dealing with applications pertaining to database. The various ways are: Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) PASSING CLASS OBJECTS TO FUNCTION Passing objects by value Passing objects by reference Passing objects by pointers Nithya, St. Xavier’s College (Autonomous) PASSING OBJECTS BY VALUE Here, only a copy of the object is passed to the function definition. The modification on the objects made in the called function will not be reflected in the calling function. Nithya, St. Xavier’s College (Autonomous) PASSING OBJECTS BY REFERENCE Here, when the objects are passed to the function definition, the formal argument of the called function, shares the memory location of the actual arguments. Hence the change made on the objects in the called function will be reflected in the calling functions also Nithya, St. Xavier’s College (Autonomous) PASSING OBJECTS BY POINTERS Here, a pointer to an object is passed. The members of the objects passed are accessed by the arrow operator (>). The change of object in the called function will be reflected in the calling function also. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) RETURNING OBJECTS FROM FUNCTIONS We are very much familiar With returning variables of built in data types. In the same way, functions can also return objects( class variables) itself to its caller. The syntax is very much similar to those that return variable of other data type to the caller. We have to prefix the type (class name )of the object while declaring the function. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) TOPICS Nested Classes Namespaces Nithya, St. Xavier’s College (Autonomous) NESTED CLASSES Class embedded within another class is called a nested class. The class which is nesting a class is known as enclosing class or outer class, and the nested class is Known as inner class. Nested classes can be defined in the private, public or protected section of the enclosing class. The name of the nested class or inner class is inside the local scope of its enclosing class. Nested classes are very rarely used. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) NAMESPACES C++ introduces a new keyword 'namespace' to define a scope that could hold global Identifiers. It enables the programmer to prevent pollution of global namespace that leads to name clashes. The best example of namespace scope is the C++ standard library, where all the classes, functions and templates are declared within the namespace std. Hence while writing a C++ program, we usually include the directive  using namespace std; Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) NAMESPACES Named Namespace Unnamed Namespace Nested Namespace Nithya, St. Xavier’s College (Autonomous) NAMED NAMESPACE The namespace that has a name is known as Named namespace Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) UNNAMED NAMESPACE Unnamed namespaces are also called anonymous namespaces. As the name indicated unnamed namespaces are those namespaces which do not have a name. The members of unnamed namespace occupy the global scope and are accessible in all scopes following the declaration in the file. This allows you to create identifiers that are known only within the scope of single file. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) NESTED NAMESPACE C++ allows nesting of a namespace within another namespace. Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) Nithya, St. Xavier’s College (Autonomous) TOPICS Static Memory Allocation Advantages of New and Delete over Calloc, malloc and free Dynamic Memory Allocation Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College STATIC MEMORY ALLOCATION Allocation of memory tor variables, during compilation time itself is known as static memory allocation Nithya Nadar,St.Xavier’s College LIMITATION OF STATIC MEMORY ALLOCATION 1. Its Sequential 2. Size of the memory cannot be expanded 3. Size of the memory cannot be shrinked. Nithya Nadar,St.Xavier’s College DYNAMIC MEMORY ALLOCATION Memory allocation in C++ can be done by making use of “New” operator. The object can be created using the "new” Operator. The new operator allocates specific amount of memory block from the free store during execution time and returns Starting address of the block allocated to a pointer. Nithya Nadar,St.Xavier’s College ADVANTAGES OF NEW AND DELETE It automatically returns the address of the correct cast reducing the programmers botheration to typecast explicitly unlike Cs memory allocation functions "calloc and "realloc“. It automatically determines the size of the data object for which the memory is allocated, which requires no "sizeof" operator, making the syntax very easy to Write, read and understand unlike C's "malloc", "calloc and realloc functions, new and "delete operators can be overloaded It is possible to initialize the object at the time of allocating the memory. Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College SYNTAX FOR MEMORY ALLOCATION 1) Memory Allocation for a single variable 2) Memory Allocation for an array 3) Memory Allocation for an object Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College Nithya Nadar,St.Xavier’s College TOPICS Static Memory De-Allocation Why Memory De-Allocation is necessary? Set_New_Handler Function Nithya Nadar, St.Xavier’s College DYNAMIC MEMORY DE-ALLOCATION The object created by 'new, i.e, the memory allocated for certain variable, by 'new operator has to be deallocted once its purpose is over. This is done by the 'delete' operator Delete operator destroys the created object to release the memory space tor future use delete is a keyword in C++. Nithya Nadar, St.Xavier’s College SYNTAX FOR MEMORY DE-ALLOCATION 1) Memory Allocation for a single variable 2) Memory Allocation for an array 3) Memory Allocation for an object Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College WHY MEMORY DE-ALLOCATION IS NECESSARY? To avoid "memory leakage". Memory leakage is a situation where, once memory is allocated dynamically for a variable and later if the allocated memory is not de-allocated after its purpose is satisfied, during the program execution, the memory gets lost. This problem, where in the memory is dynamically allocated or reserved but not released and hence not accessible to any of the program is called "memory leakage" Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College SET_NEW_HANDLER FUNCTION If memory is allocated successfully then the address is returned but is if its unsuccessful then NULL is returned by new operator. If the new operator doesn’t find the block of memory large enough to hold the desired object then a special function known as the _new_handler( )' is called. There is an internal pointer to a function is checked, and if the pointer is non-zero, then the function it points to is called. This default behavior can be changed i.e., if the "new operator fails to allocate the desired memory for an object, instead of returning a NULL, we could write a function which prints the error message and exits the program for debugging purpose. To change this default behaviour, we make use of SET_NEW_HANDLER function. Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College Nithya Nadar, St.Xavier’s College TOPICS Constructor Characteristics of Constructor Nithya Nadar, St. Xavier’s College CONSTRUCTOR Constructor is a special function used to initialize class data members or we can say constructor is used to initialize the object of class. Constructor is a class member function with same name as the class. Constructor is automatically invoked when object is created. The main job of constructor is to allocate memory for class objects. Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College CHARACTERISTICS OF CONSTRUCTOR Constructor name and class name must be same. Constructor doesn't return value. Constructor is invoked automatically, when the object of class is created. Constructor has no return type even void. They can not be inherited. These cannot be static. They can be declared in public or private section but it is preferred to declare it in the public section for availability to all the functions. If declared as private, it can be accessed only by its class members. We can not create virtual constructor We can overload constructor Nithya Nadar, St. Xavier’s College TOPICS Destructor Characteristics of Destructor Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College DESTRUCTOR Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope. The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ^' sign as prefix to it. Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College CHARACTERISTICS OF DESTRUCTOR Destructor name and class name must be same with a tilde sign. Destructor doesn't return value. Destructor is invoked automatically, when compiler comes out form the function where an object is created. Destructor has no return type , no arguments. We cannot overload destructor. They should be declared in public section. It is necessary that a destructor use the delete expression to de-allocate the memory, if the constructor in the program uses the new expression for allocating the memory. Destructor is called in the reverse order of its constructor invocation. Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College Nithya Nadar, St. Xavier’s College TOPICS What is Inheritance? Advantages of Inheritance Protected Access Specifier WHAT IS INHERITANCE? Inheritance is a feature, or a process where a new class is created from an existing class. The new class is known as derived class or child class. The existing class is known as base class or parent class. When a derived class inherits base class, it inherits all the properties of the base class. The derived class can use the properties of base class without changing and also can add new properties to its own. The new properties added will not affect the base class. SYNTAX OF INHERITANCE class : EXAMPLE OF INHERITANCE class x { // Features of class x }; class y : public x { // Features of class y }; ADVANTAGES OF INHERITANCE Code re-usability Ability to add extra features without disturbing the base class. THE PROTECTED ACCESS SPECIFIER This access specifier is extensively used in inheritance. The members declared in this section can be accessed only by the class member functions as well as friends of this class. It is not accessible outside the class purview. The members declared in this section can be inherited. DERIVING FROM THE EXISTING CLASS “PUBLICLY” The member functions of the derived class, the member function of subsequently derived classes as well as the non-member functions cannot access the private members of the base class. The member functions of the derived class, the member function of subsequently derived classes as well as the non-member functions can access the public members of the base class. It means the public members of base class remains public when inherited. The member functions of the derived class, the member function of subsequently derived classes can access the protected members of the base class. The non-member functions cannot access the protected members of the base class. It means the protected members of base class remains protected when inherited. DERIVING FROM THE EXISTING CLASS “PROTECTEDLY” The member functions of the derived class, the member function of subsequently derived classes as well as the non-member functions cannot access the private members of the base class. The member functions of the derived class, the member function of subsequently derived classes can access the public members of the base class. The non-member functions cannot access the public members of the base class using the objects of derived as well as subsequently derived class. It means the public members of base class becomes protected when inherited. The member functions of the derived class, the member function of subsequently derived classes can access the protected members of the base class. The non-member functions cannot access the protected members of the base class. It means the protected members of base class remains protected when inherited. DERIVING FROM THE EXISTING CLASS “PRIVATELY” The member functions of the derived class, the member function of subsequently derived classes as well as the non- member functions cannot access the private members of the base class. The member functions of the derived class can access the public members of the base class. The member functions of subsequently derived classes cannot access the public members of the base class. The non-member functions also cannot access the public members of the base class. The member functions of the derived class can access the protected members of the base class. The member function of subsequently derived classes cannot access the protected members of the base class. The non-member functions cannot access the protected members of the base class. It means the protected members of base class becomes private when inherited. DIFFERENT TYPES OF INHERITANCE Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance SINGLE INHERITANCE When a single class is derived out of a single base class, it is known as single inheritance. There is one-to-one relationship between the base class and the derived class. The existing class is called as direct base class. The new class is known as singly inherited class. MULTIPLE INHERITANCE It is a process in which a child can be inherited from more than one base class is known as multiple inheritance. The child can inherit the feature from all the parents or the base classes. MULTILEVEL INHERITANCE It is a process in which a base class is inherited by its derived class, which in turn is inherited by its child class and so on is known as multilevel inheritance. This process includes the chaining of single inheritance with multiple derived classes and a single base class. Here the base class is known as super class. HIERARCHICAL INHERITANCE It is a process in which a parent class(base class) can be inherited by more than one child class is known as hierarchical inheritance. These inherited child classes can again serve as a base class for other child classes. This type of inheritance follows one-to-many relationship. HYBRID INHERITANCE It is process in which different forms of inheritance involved in a program design. The pictorial representation shows the mixture of multiple and multilevel inheritance. FUNCTION OVERRIDING A mechanism of defining a function with the same name and signature in both the base class as well as derived class is known as function overriding. If you create an object of derived class and write code to access that member function then, the member function in derived class is only invoked, i.e., the member function of derived class overrides the member function of base class. ACCESSING THE OVERRIDDEN FUNCTION IN BASE CLASS FROM DERIVED CLASS To access the overridden function of base class from derived class, scope resolution operator :: is to be used. For example: If you want to access get_data() function 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. WHAT IS POLYMORPHISM? Polymorphism means having multiple forms. The origin of the word comes from two greek term “poly”(many) and “morphos”(form). COMPILE-TIME POLYMORPHISM This type of polymorphism is achieved through “Function Overloading” and “Operator Overloading”. In function Overloading the member functions with the same name and different arguments help the compiler to bind the appropriate function during compile time itself. This binding is called static binding. Hence polymorphism is achieved during compile- time. RUN-TIME POLYMORPHISM This type of polymorphism is achieved through “Virtual Functions”. Here binding of a function definition to a specific function call is done during run- time. Hence polymorphism is achieved during run-time. POINTERS TO DERIVED CLASS Two types of pointers pointing to derived class object: 1. Pointer of type derived class pointing to derived class object. 2. Pointer of type base class pointing to a derived class object. TWO WAYS TO OVERCOME 1. TypeCasting the pointers 2. Using Virtual Functions NEED OF VIRTUAL FUNCTION In the concept of function overriding, if a derived class pointer points to the derived class object, it invokes the member function in the derived class and displays its content. And when a base class pointer points to the derived class object, it always invokes the member function in the base class and displays its content. This happens because the compiler simply ignores the contents of the pointer and chooses the member functions that matches the type of pointer. This violates the rule of polymorphism. Hence we can achieve polymorphism using virtual functions. VIRTUAL FUNCTIONS When we use the function with the same name and same signature in both the base and derived classes, the function in the base class is declared as virtual using the keyword “Virtual” prefixed with the function declaration. When a function is made virtual, the decision as to which function to be invoked is done at run-time based on the type of the object pointed by the pointer rather than the type of the pointer. The keyword is required only in declaration not in definition. Once a function is made virtual in base class, it is virtual for all the derived classes. SYNTAX OF VIRTUAL FUNCTION virtual () OR virtual () RULES FOR VIRTUAL FUNCTIONS The virtual functions must be non-static. The virtual functions are accessed by using the pointers to objects. A virtual function can be friend of another class. Constructor cannot be made virtual but destructors can be virtual. Virtual function defined in the base class need not be necessarily redefined in the derived class. A base class pointer can refer to the derived class objects but reverse is not true. Virtual functions should be declared in the public section of a class. FEATURES OF PURE VIRTUAL FUNCTIONS Pure Virtual Function is a do-nothing function. When the base class uses a pure virtual function, each of its derived class must override that function, failing of which a compile-time error is generated. A class containing a pure virtual function is called as an Abstract class. If a virtual function is declared as pure, it must be redefined in each derived class, else the compilation of the program is unsuccessful. A class having pure virtual function cannot be used to instantiate object of its own. INTERNALS OF VIRTUAL FUNCTIONS Here we will see how the virtual function works. During compile-time, a table known as virtual table also known as VTBL is created for both base class and derived class. This table contains the addresses of only the virtual functions in the corresponding class. The address of the non-virtual function is not stored in VTBL. Example: Class A { public: void virtual xyz(); void virtual pqr(); }; DURING RUN-TIME THE FOLLOWING VTBL WILL BE GENERATED FOR CLASS A: Address of A::xyz() Address of A::pqr() 2000 3000 Class B : public A { public: void virtual jkf(); void pqr(); }; Address of Address of Address of B::xyz() B::pqr() B::jkf() 2000 4000 5000 POINTS TO BE NOTED If the derived class contains an overriding function, then the VTBL of the derived class contains a new address for the overriding function. If a derived class declares a new virtual function, its VTBL contains the address of new virtual function. If the derived class does not redefine a certain base class virtual function, then the VTBL of the derived class will contain the address of the inherited base class function itself. Every object of a class containing a virtual function contains a pointer to the VTBL of that corresponding class. The pointer is known as VPTR. Whenever a virtual function is called through an object or a reference to an object or through a pointer to an object, the value of VPTR is read first and then the address of the called function is obtained from VTBL. Finally the function is called through the address thus obtained. This is how virtual functions work. It is important to note that the size of the objects of classes with virtual function increases uniformly by four bytes due to the presence of additional pointer. VIRTUAL DESTRUCTOR Destructors are always called in the reverse order of constructor invocation. The concept of virtual destructor comes into picture when the objects in the derived class are created using the new operator. Let us study a scenario where a base class pointer contains the address of the derived class object obtained dynamically using the new operator. SCENARIO int main() { A *aptr; aptr = new B; ……….. ……….. delete aptr; } When we delete the base class pointer containing the address of the derived class object, the base class destructor is called instead of derived class destructor. As the derived class destructor is not called up, it leads to memory leaks. To avoid this destructor has to be virtual in the base class. SEQUENCE OF CALLING Base class constructor called Derived class constructor called Derived class destructor called Base class destructor called FAMOUS DIAMOND PROBLEM In this scenario, class B and class C are derived from class A. So both the classes will have the data members and member functions of class A. Now class D is derived from class B and class C. So Class D will inherit all the members of class B and class C. If class D wants to Access the members of class A, an ambiguity problem of which of the two copies to be accessed will be raised. This is the famous Diamond problem. VIRTUAL BASE CLASSES To solve the famous diamond problem the concept of virtual base classes was introduced. The ambiguity problem disappears when class A is declared virtual for class B and class C. This can be done by using “virtual” keyword prefixed with the base class for derived class B and C. PURE VIRTUAL FUNCTION A virtual function that is declared but not defined in the base class is referred to as a pure virtual function. Syntax:. virtual (args>) = 0; OR virtual (args>) = 0; It should be noted that here the function is initialized to zero. The assignment operator has nothing to do with assignment, means, the value is not assigned to anything. It is used simply to inform compiler that the function will be pure and does not have any body. FEATURES OF PURE VIRTUAL FUNCTIONS Pure Virtual Function is a do-nothing function. When the base class uses a pure virtual function, each of its derived class must override that function, failing of which a compile-time error is generated. A class containing a pure virtual function is called as an Abstract class. If a virtual function is declared as pure, it must be redefined in each derived class, else the compilation of the program is unsuccessful. A class having pure virtual function cannot be used to instantiate object of its own. ABSTRACT CLASS A class that contains at least one pure virtual function is known as an abstract class. It is a design concept only to act as a base class upon which other derived classes are set up. An object of an abstract class cannot be created while pointers can be created of it. There can be any number of abstract classes in class hierarchy. LIMITATIONS OF VIRTUAL FUNCTIONS Global functions cannot be declared as virtual. Defining a virtual function in the base class is a must, even though it may not be used. Virtual function cannot be declared as static because static functions can be invoked without referencing a specific class instantiation. There is virtual destructor but no virtual constructor. E A R LY B I N D I N G L AT E B I N D I N G Function call is binded with Function call is binded with the Code to be executed the Code to be executed during compile time during run time Examples are: Operator Example is Virtual Function overloading and Function Overloading Resolved during Compile Resolved during runtime time Lacks Flexibility More Flexible Operator Overloading Chap-8 What is operator overloading  Operator overloading is a compile- time polymorphism.  It is an idea of giving special meanings to an existing operator.  The original meaning cannot be changed.  It means that an additional meaning is given with the existing ones.  The operator precedence as well as the syntax cannot be changed. For Example Int a; Float b, sum; Sum = a+b;  Here variables a and b both are of built-in data types.  Hence the contents of variable a and b can be easily added. Class A { }; Int main() { A a1,a2,a3; A3 = a1 +a2; }  Here “a1” and “a2” are objects  So to make operator + to add two objects, user has to redefine the meaning of + operator.  This is done using operator overloading. We can overload  Unary Operators (operators operating on one operand)  Binary Operators (operators operating on two operands)  Special Operators (ex. [], () etc.) How to overload operators?  To redefine an operator, a function known as operator function has to be created.  It is mandatory.  By using operator function we can overload different operators as per our requirement. OVERLOADING UNARY OPERATOR USING MEMBER FUNCTION  Unary operators are those operators which operate on one operand.  Giving an additional meaning means we have to define a separate function for that job.  When we want to overload unary operator using member function; it means that operator functions must belong to the class.  To overload unary operator using member operator function, it should have zero argument. Syntax of operator function  Function Prototype operator op();  Function Definition classname :: operator op() { }  Here, operator is a keyword and op means the operator to be overloaded. THE STATEMENT –S IS CONVERTED BY COMPILER DURING COMPILE TIME TO::> S.OPERATOR –() ANOTHER WAY OVERLOADING UNARY OPERATOR USING FRIEND FUNCTION Syntax  Function Prototype friend operator op();  Function Definition operator op() { }  Here, operator is a keyword and op means the operator to be overloaded.  Here the operator function is not the member of the class.  So the operator function has to be declared as friend of the class at first.  As we are making the operator function, friend of our class, it is known as friend operator function.  The Statement: -S; Is converted by compiler to: Operator –(s) OVERLOADING BINARY OPERATOR USING MEMBER FUNCTION  Overloading binary operator means making the binary operator work on the user- defined types; means class objects.  To overload binary operator using member function, one explicit arguments has to be passed in operator function.  If operator function is a member function then the syntax for overloading binary operator is as follows:  Function Prototype operator op();  Function Definition :: operator op() { }  Here, operator is a keyword and op means the operator to be overloaded.  The Statement: S3=S1+S2; Is converted by compiler to: S3=S1.operator +(S2) OVERLOADING BINARY OPERATOR USING FRIEND FUNCTION  Here the operator function is not the member of the class.  So the operator function has to be declared as friend of the class at first.  To overload binary operator using friend function, two explicit arguments has to be passed in the operator function. Syntax  Function Prototype friend operator op();  Function Definition operator op() { }  Here, operator is a keyword and op means the operator to be overloaded.  The Statement: S3=S1+S2; Is converted by compiler to: S3=operator +(S1,S2) Rules of Operator Overloading  Operators such as scope resolution operator, conditional operator, sizeof operator, typeid operator etc cannot be overloaded.  New operators cannot be created by our own for overloading. Ex. +++  Operators such as +,-, and many other operators can be overloaded.  Predefined meaning of an operator cannot be changed.  Semantics can be extended but syntax cannot be changed.  The operators such as assignment operator, function operator, subscript operator and pointer to member access operator(->) cannot be overloaded using friend function or static function.  When unary operators are overloaded using member function, it takes no explicit argument.  When unary operators are overloaded using friend function, it takes one explicit argument.  When binary operators are overloaded using member function, it takes one explicit argument.  When binary operators are overloaded using friend function, it takes two explicit arguments. Note…  List of operators that cannot be overloaded using friend or static function: Table 8.3 page 233  List of operators that cannot be overloaded: Table 8.1 page 215  List of operators that can be overloaded: Table 8.2 page 215 List of operators that cannot be overloaded using friend or static function Why to overload operators using friend function?  During operator overloading, the interpretation of the compiler matters a lot.  For the statement: S3 = s1 + s2; The compiler will interpret as: S3= s1.operator(s2); Which means that binary operator “+” is overloaded by using member function.  Now suppose we try to overload binary operator “+” using member function and write the following code then: S3 = s1 + 5;  Here 5 is a constant value while s1 is an object so it will work.  But if the code is written like: S3 = 5 + s1;  Then it wont work and compiler will generate an error because it is not able to get one implicit parameter.  That’s why friend function is needed for such scenario. CHAPTER 8 ENDS Chapter - 9  Whenever an assignment operator is used to assign a value from one variable to another with different data types, then type conversion is done automatically.  For example: int a; float b; b = 5.55; a=b;  In above example both are the basic data types, due to which conversions are done automatically.  But what can be done when basic as well as user-defined data types both are involved.  Conversion from basic type to class type  Conversion from class type to basic type  Conversion from one class type to another class type.  In this type of conversion, source is of the basic data type while the target is of class type.  It means that conversion has to be done from basic data type to an object.  To perform this type of conversion, a parameterized constructors must be placed in the target(means in class).  The constructor must take only one argument of the basic data type from which it is converted into an object.  In this type of conversion, source is of the class data type while the target is of basic type.  It means that conversion has to be done from an object to a basic data type.  It cannot be achieved by placing constructors but an operator function has to placed in the source.  The operator function is also known as type- conversion function. Operator type() { //Function Body } Where, Operator = keyword to create a type conversion function. Type = target type to which an object is to be converted.  It must have no arguments.  It must be a class member function.  It must not specify a return type but should return a value.  In this type of conversion both source and target are of user-defined data type.  In short, an object is to be converted into an object of another class.  Either constructor or type-conversion function can be used to achieve this.  The constructor must take only one argument of the class data type and should be placed in the target.  The type-conversion function has to be placed in the source. First Way Second Way Case 1: Case 2: Case 3: Case 4: Case 5: Case 6: Case 7:  When the derived class object is created , the compiler looks for the zero-argument constructor by default in the base class.  If there is constructor by default in the base class, the following condition must be satisfied:  The base class must have a zero-argument constructor.  If it does not have a zero-argument constructor and has a parameterized constructor, then they must be explicitly invoked; otherwise the compiler generates an error. Case 8: Case 9: Chap-10  The overloaded functions have same name and are normally used to execute the similar kind of operations on different data types.  In the example, each overloaded function definition does identical tasks. The only change is in the data types.  This is the disadvantage of overloaded function that we need to write separate code for different data types even if the task is same.  Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.  A template is a blueprint or formula for creating a generic class or a function.  Templates can be used for function as well as classes.  A function template by itself is not a type, or a function, or any other entity.  No code is generated from a source file that contains only template definitions.  In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template).  During template instantiation, template is substituted with various built-in as well as user-defined data types.  The process of substituting template with various built-in as well as user-defined data types is known as template instantiation.  Function Templates can have more than one template parameter.  In other words, We can use more than one generic data type in the template statement as shown in the example:  Like Normal functions, function template can be overloaded.  Overloaded function must differ in either the number of parameters it is expecting or the data types of these parameters or both.  The compiler resolves the function call in the following order:  Firstly, the compiler tries to call an ordinary function. If exact match is found then the function is called up and executed.  If the first step fails then, the compiler considers the template function; substituting the data types it matches the functions return type, number of parameters, sequence as well as data type of parameters. If match is found then the function is called up and executed.  When the second step fails then, compiler tries normal overloading resolutions to ordinary functions and calls the function definition that matches and returns.  Only if the above three steps fails, an error message is generated.  Just as we can define function templates, we can also define class templates.  A class template defines a family of classes.  A class template by itself is not a type, or an object, or any other entity.  No code is generated from a source file that contains only template definitions.  In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class. class_name objectname;  Like function templates, class templates can also have multiple parameters.  Consider the following example:  Reduced source code  Less disk space needed to store files.  Easy to debug the program.  Good documentability.  Templates can be embedded or defined within a class or a class templates.  They are referred as member templates.  Member templates that are classes are referred to as nested class templates.  Nested class templates are declared as class templates inside the scope of outer class.

Use Quizgecko on...
Browser
Browser