Anda di halaman 1dari 114

Procedure Oriented Programming

In the POP approach, the problem is viewed as a sequence of things to be done such as reading, calculating, and printing. A number of functions are written to accomplish these tasks. The primary focus is on Functions.
1

POP Approach Diagram


Main Program Function-1 Function-2 Function-3

Function-4 Function-6

Function-5 Function-8
2

Function-7

In multi-function programming , many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data.

Global data Function-1 Local data

Global data Function-2 Local data Function-3 Local data


3

Drawbacks in POP Approach


Global data are move openly around the system

from function to function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. Note: POP approach does not model real world problems very well, because functions are action-oriented and do not really correspond to the elements of the problem.
4

Object-Oriented Programming
Object Oriented Programming treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions.
5

OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The data of an object can be accessed only by the functions associated with that objects. The functions of one object can access the functions of other objects.
6

OOPs Approach Diagram Object A Object B Data


Communication

Data
Functions

Functions

Object C Functions
Data
7

OOPs principle
Encapsulation and Data Hiding: The wrapping up of data and functions into a single unit (called class) is known as encapsulation. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide the interface between the objects data and the program.
8

Key concepts of OOP


1.Object: Objects are primary run-time entities in an object oriented programming. An object is a specimen of a class. Objects occupy space in memory. Every object has its own properties or features. The action of the object depends upon the member function defined within its class.
9

Commonly available objects

10

2.Classes:

A class is grouping of objects having identical properties, common behavior, and shared relationship. The entire group of data and code of an object can be built as a user-defined data type using class. Objects are nothing but variables of type class. Once a class has been declared, the programmer can create a number of objects associated with that class.
11

v
Actions:

Class :

Bus

Properties: Actions:

company, model,
color, capacity

speed(), average()

Class : Properties:

computer brand, price, hard disk, RAM size processing speed(), display()
12

3.Method:

An operation required for an object when coded in a class is called method. The operations are to be defined in a class. All objects in a class perform certain common actions or operations.
A class contains private data members and public methods or member functions. Generally the data members are declared private and member functions are declared public.
13

4. Data Abstraction Abstraction directs to the procedure of representing essential features without including the background details. Class uses the theory of abstraction and is defined as a list of abstract properties such as size, cost, height and a few functions to operate on these properties.

14

5. Encapsulation:
The packing of data and functions into a single component is called encapsulation. Data hiding can be accomplished with encapsulation. In c++, the data is not accessible by outside functions. Only those functions that are able to access the data are defined within the class.

15

6.Inheritance:

Inheritance is the method by which objects of one class get the properties of objects of another. In object oriented programming, inheritance provides the thought of reusability. The programmer can add new properties to the existing class without changing it.

16

7.Polymorphism:

Polymorphism allows the same function to act differently in different classes.


Line Display()

Dotted objects

Display()

stars Display()

Asterisk Display()
17

Streams in C++:

C++ provides a new way to perform the input and output operations called iostream method.
The standard header file iostream.h contains a set of small and specific general purpose functions for handling input and output data.

The standard input and output operations in C++ are normally performed by using the I/O stream as cin for input and cout for output.

18

cout:

Syntax:
cout<<var1<<var2<<<<varn cin: Syntax:

cin>>var1>>var2>>.>>varn;
19

Frequently used unformatted input and output functions:


get()

cin

getline()
read() put()

cout

write()
20

get() and put() functions:

The single character input and output operations in c++ can be done with the help of these functions.
The get() is used to read a character and the put() is used to display the character on the screen. The syntax is: cin.get(ch) cout.put(ch)
21

getline(), read() and write():

The getline() and write() functions are useful in string input and output. The getline() reads the string including white spaces.
The object cin calls the function as:

cin.getline(variable, size);

22

read():

It also reads the text through the keyboard.


Syn: cin.read(variable,size); When we use read statement it is necessary to enter character equal to the number of size of specified. The getline() statement terminates the accepting data when enter is pressed where as the read() continues to read characters till the no. of characters entered are equal to the size specified.
23

write(): The write() function is used to display the string on the screen. Its format is the same as getline() but the function is exactly opposite. Syn: cout.write(variable, size); The cout.write() statement displays only specified number of characters given in the second argument, though actual string may be more in length.

24

Manipulator functions:

These are special stream functions that change certain characteristics of the input and output. The main advantage of these is that they facilitate the formatting of input and output streams.
To carry out the operations of these in a user program, the header file input and output manipulator <iomanip> must be included.
25

Predefined manipulators:

endl
hex, dec, oct setbase setw setfill

setprecision
ws
26

1.The endl is an output manipulator to generate a carriage return.

2. The setbase() manipulator is used to convert the base of one numeric value into another base. Following are the common base converters. dec (base 10) hex (base 16) oct (base 8)
27

3.

The setw() stands for the set width. It is used to specify the minimum no. of character positions on the output field a variable will consume. The setfill() manipulator function is used to specify a different character to fill the unused field width of the value. The setprecision() is used to control the number of digits of an ouput stream display of a floating point value.
28

4.

5.

Flags:

Format
Left justification Right justification Fixed point notation Decimal base

Flag
ios::left ios::right ios::fixed ios::dec

Octal base
Hexadecimal base

ios::oct
ios::hex
29

showpoint: The showpoint flat is used to show the decimal point for all floating point values. By default, the number of decimal position is six. Syntax: cout.setf(ios::showpoint); Precision: The precision member function is used to display the floating point value as defined by the user. Syntax: cout.precision(int n);
30

scientific: When scientific is set, floating point values are inserted using scientific notation. There is only one digit before the decimal point followed by the specific number of precision digits which in turn is followed by an e(exponent value).

Syntax: cout.setf(ios::scientific, ios::floatfield);

31

fixed: When fixed is set, the value is inserted using decimal notation with the specified number of precision digits following the decimal point. Syntax: cout.setf(ios::fixed, ios::floatfield);

32

Left: If left is set, the inserted data will be flush left in a field of characters width wide. The extra space, if any, will be filled by the fill character. Syntax: cout.setf(ios::left, ios::adjustfield); Right: Cout.setf(ios::right, ios::adjustfield);

33

Some important keywords in c++:


catch friend operator public throw class inline private template try delete new protected this virtual
34

Dynamic initialization:

The declaration and initialization of variable in a single statement at any place in the program is called dynamic initialization.
In C, initialization of variables can be done at any place but the variable must be declared at the beginning of the program.

35

Operators in C++:

Operator
<<

Description
insertion operator

>>
:: delete new &

extraction operator
scope access (or resolution) operator memory release operator memory allocation operator referencing operator
36

Referencing operator(&):

The referencing operator is used to define referencing variable. A reference variable an alternative name for previously defined variable.
Syn: data_type ref_var_name = var_name Ex: int a = 10; int &b = a; If we modify the value of a, it results in change in reference variable too. Note: Array of references is not allowed.
37

Scope access operator:

The scope access operator (::) allows a programmer to access a global name even if it is hidden by a local re-declaration of that name.

38

Memory management operators:

In C, we have had the functions malloc(), calloc() and realloc() to allocate memory dynamically at runtime in the program. The free() function is used to release the resources allocated by these functions. C++ also allows us to use these.
In addition, C++ provides us with two new operators new and delete. The new operator creates an object and delete destroys it.
39

The advantages of new operator over malloc(): 1.The new operator itself calculates the size of the object with the use of sizeof operator. 2.It returns the pointer type. The programmers need not take care of type casting.

3.The new operator allocates memory and initializes the object at once. 4.The new and delete operators are very easy in syntax. They can be overloaded.
40

The new operator:

pointer memory variable = new data type[size];


Ex: pv = new int;

pv is a pointer variable of int type.


int *pv = new int(50);

Here, 50 is assigned to pointer variable pv.


*p = new int[3];

Here, memory for 3 integers (6 bytes) are assigned to pointer variable p.


41

The delete operator:

Syntax:
delete <pointer memory variable>

delete[element size]<pointer mem_var>


Ex:

delete p;
delete[5]p or delete[]p;

42

Functions with Default arguments:


C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which doesnt have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.

43

Declaration of a class:

A class definition is a process consisting the following steps:


1.Definition of a class. 2.The internal representation of data structures and storage. 3.The internal implementation of the interface. 4.The external operations for accessing and manipulating the instance (object) of the class.
44

Class and Objects


A class is used to pack data and functions together. The class has a mechanism to prevent direct access to its members, which is the central idea of oop. Syntax: <class> <class_name> { private:<member_list> public: <member_list> };

45

Declaration of objects: A class declaration builds the structure of object. The member variables and functions are combined in the class. The declaration of object is same as declaration of variables data types. Defining objects of class type is known as class instantiation.

46

An object is an abstract unit having following properties: 1.It is an individual. 2.It points to a thing, either physical or logical that is identifiable by the user. 3.It holds data as well as operation method that handles data. 4.Its scope is limited to the block in which it is defined.
47

Private member function:

To execute private member function, it must be invoked by public member function of the same class. A member function of a class can invoke any other member function of its own class. This method of invoking function is known as nesting of member functions.

48

Member function outside the class:

To define a function outside the class ,


1.The prototype of function must be declared inside the class. 2.The function name must be preceded by class name and its return type separated by scope access operator.

49

Inline function: In C++, you can create short functions that are not actually called; rather, their code is expanded in line at the point of each invocation. This process is similar to using a function-like macro. To cause a function to be expanded in line rather than called, precede its definition with the inline keyword. Syntax: inline <ret_type> <fun_name> { function body }
50

Since classes typically require several frequently executed interface functions, the efficiency of these functions are of critical concern. Each time a function is called, a significant amount of overhead is generated by the calling and return mechanism. Typically, arguments are pushed onto the stack and various registers are saved when a function is called, and then restored when the function returns. These instructions take time.
51

However, when a function is expanded in line, none of those operations occur. Although expanding function calls in line can produce faster run times, it can also result in larger code size because of duplicated code. For this reason, it is best to inline only very small functions.
52

Ouside member function inline:

An inline member function is similar to macros. Call to inline function in the program, puts the function code in the caller program. This is knows as inline expansion. Inline functions are also called open subroutines because their code is replaced at the place of function call in the caller function. The normal functions are called closed subroutines because when such functions are called, the control passes to the function.
By default all member functions defined inside the class are inline functions.

53

The member function defined outside the class can be made inline by prefixing the keyword inline to function declarator.

Inline return_type class_name :: function name(argument list)

54

Memory allocation for object :


Common for all objects
Member function 1 Member function 2

Memory created when Object functions defined 1 Object 2

Member variable1
Member variable2

Member variable1
Member variable2
55

Memory created when

The memory space for objects is allocated only when they are declared and not when the class is specified. Actually, the member functions are created and placed in the memory space only when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions. Only space for member variables is allocated separately for each object. This is essential because the member variables will hold different data values for different objects.
56

Static Data Members When we declare a member variable static, we are telling the compiler that only one copy of that variable will exist and that all objects of the class will share that variable. Unlike regular data members, individual copies of a static member variable are not made for each object. No matter how many objects of a class are created, only one copy of a static data member exists. Thus, all objects of that class use that same variable. All static variables are initialized to zero before the first object is created.
57

Object A

Object B

var1 var2 varn Static variable


Object C

var1 var2 varn

var1 var2 varn

58

Note: The type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than as part of an object. They are also known as class variables.

59

static member functions We can also declare member functions as static such a functions are called as static member functions.

Characteristics: A static function can have access to only other static members (functions or variables) declared in same class. A static member function can be called using the class name (instead of its objects) .
60

Static object: In C, it is common to declare variable static that gets initialized to zero. The object is a composition of one or more variables. The keyword static can be used to initialize all class data member variables to zero. Declaring object itself as static can do that. Thus, all its associated members get initialized to zero.

61

Friend Functions The private members cannot be accessed from outside the class. That is, a non-member function cannot have an access to the private data of a class. When a private data member is changed to public category, it violates the whole concept of data hiding and data encapsulation. To solve this problem, a friend function can be declared to have access to these data members.
62

Friend is a special mechanism for letting nonmember functions access private data. A friend function may be either declared or defined within the scope of a class definition. The keyword friend inform the compiler that it is not a member function of the class. Syntax: Friend return_type fun_name(parameters);

63

Granting friendship to another class: A class can have friendship with another class. For example, let there be two classes, first and second. If the class first grants friendship with the other class second, then the private data members of the class first are permitted to be accessed by the public member functions of the class second. But on the other hand, the public member functions of the class first cannot access the private members of the class second.
64

The general syntax: Class second;//forward declaration Class first { private: Public: friend ret_type fun_name(class first, class second); }; Class second { private: public: friend ret_type fun_name(class first, class second); };
65

Two classes having the same friend: A non-member function may have friendship with one or more classes. When a function has declared to have friendship with more than one class, the friend classes should have forward declaration. It implies that it needs to access the private members of both classes.

66

A friend function can be called by reference. In this case, local copies of the objects are not made. Instead, a pointer to the address of the object is passed and the called function directly works on the actual object used in the call.

67

Constructors and destructors A constructor is a special member function whose task is to initialize the objects of its class. The constructor is invoked whenever an object of its associated class is created. Its name is same as the class name. A destructor is used to destroy the objects that have been created by a constructor. Its name is the same as class name but preceded by a tilde(~) operator.
68

Characteristics of constructors: 1. Constructor has the same name as that of the class it belongs. 2. Constructor is executed when an object is declared 3. Constructors have neither return value nor void. 4. The main function of constructor is to initialize objects and allocate appropriate memory to objects. 5. Constructors without arguments are called default arguments.
69

Constructors with arguments: The constructors with arguments are called parameterized constructors. For these constructors, it is necessary to pass values to the constructor when object is created.

70

Function overloading:
In C++, it is possible to use the same function for a number of times for different intentions. Defining multiple functions with same name is called function overloading or function polymorphism. The overloaded function must be different in its argument list and with different data types.

71

Principles of function overloading: 1. If two functions have the similar type and number of arguments (data type), the function cannot be overloaded. sum(int, int, int); sum(int, int); sum(int, int, int); sum(float, float, float); These two can be overloaded.
72

2. The compiler attempts to find an accurate function definition that matches in types and number of arguments and invokes that function. The arguments passed are checked with all declared functions. If matching function is found then that function gets executed. 3. If there is no accurate match found, compiler makes the implicit conversion of actual argument. For example, char is converted to int and float is converted to double.
73

Overloading constructors: Like functions, it is also possible to overload constructors. A class can contain more than one constructor. This is called constructor overloading. All constructors are defined with the same name as the class. All the constructors contain different number of arguments. Depending upon number of arguments, the compiler executes appropriate constructor.

74

Constructors with default arguments: Like functions, it is also possible to declare constructors with default arguments.

75

Destructors: Destructor is a special member function like constructor. Destructors destroy the class objects created by constructors. The destructors have the same name as their class, preceded by tilde (~). For local and non-static objects, the destructor is executed when the object goes out of the scope. In case the program is terminated by using return statements, the destructor is executed for every object existing at that time. It is not possible to define more than one destructor. The destructor is only one way to destroy the object.
76

Operator overloading: C++ has the ability to treat user-defined data type like the one they were built-in type. User-defined data types created from class or struct are nothing but combination of one or more variables of basic data types. The compiler knows how to perform various operations using operators for built-in types. The compiler would throw an error if we want to perform an operation between two objects using operators. Therefore, for the objects, the operation routine must be defined by the programmer.
77

The key word operator defines a new action or operation to the operator. Syntax: Return_type operator op_symbol(parameters) { statement 1; statement 2; } The keyword operator, followed by an operator symbol, defines a new (overloaded) action of the given operator.
78

Rules for overloading operators: 1. Overloading of an operator cannot change the basic idea of an operator. When an operator is overloaded, its properties like syntax, precedence and associatively remain constant. Ex: a+ = b; is a=a+b; 2. Overloading of an operator must never change its natural meaning. An overloaded operator + can be used for subtraction of two objects, but this type of code decreases the utility of the program.

79

When ++ and operators are overloaded, the system cant determine whether the operators are overloaded for prefix or postfix operations. Hence, the operator must be overloaded in such a way that it will for both prefix and postfix operations. To make a distinction between prefix and postfix notation, a new syntax is used to indicate postfix operator overloading function. The syntaxes are: operator ++ (int) //postfix notation operator ++() //prefix notation

80

Inheritance:
Using inheritance, we can create a general class that defines traits common to a set of related items. This class may then be inherited by other, more specific classes, each adding only those things that are unique to the inheriting class. In keeping with standard C++ terminology, a class that is inherited is referred to as a base class. The class that does the inheriting is called the derived class. Further, a derived class can be used as a base class for another derived class. In this way, multiple inheritance is achieved.
81

Class inheritance uses this general form: class derived-class-name: access base-class-name { // body of class }; The access status of the base-class members inside the derived class is determined by access.

82

Private inheritance: When a base class is privately inherited by a derived class, public and protected members of the base class become the private members of the derived class. Therefore the public members of the base class can only be accessed by the member functions of the derived class.

83

Public inheritance: When a base class is publicly inherited by a derived class, public members of the base class become the public members of the derived class and protected members of the base class become the protected members of the derived class. Therefore public members of the base class can accessible to the objects of the derived class.

84

Protected inheritance: When the base class is protectedly inherited by a derived class, public and protected members of the base class become the protected members of the derived class. Therefore public members of the base class can be accessed by the member functions of the derived class.

85

Inheritance and protected Members: A private member of a base class is not accessible by other parts of our program, including any derived class. However, protected members behave differently. If the base class is inherited as public, then the base class' protected members become protected members of the derived class and are, therefore, accessible by the derived class. By using protected, you can create class members that are private to their class but that can still be inherited and accessed by a derived class.
86

Note: When a derived class is used as a base class for another derived class, any protected member of the initial base class that is inherited (as public) by the first derived class may also be inherited as protected again by a second derived class.

87

Types of inheritance: 1. Single inheritance: If a class inherits from one base class is called single inheritance. 2. Multiple inheritance: If a class inherits from more than one base class is called multiple inheritance. 3. Multilevel inheritance: If a class derived from a derived class is class multilevel inheritance. 4. Hierarchical inheritance: The mechanism of deriving more than one derived class is called hierarchical inheritance.
88

Constructors in inheritance

89

Case-1: When base class has default constructor(without arguments), the derived class need not have a constructor function. case-2: However, if any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor with arguments and pass the arguments to the base class constructors.

90

while applying inheritance we usually create objects using the derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. The constructor of the derived class receives the entire list of values as its arguments and passes them on to the base class constructors in the order in which they are declared in the base class. When both the derived and base classes contain constructors, the base class constructor is executed first and then the derived class constructor is executed next.
91

C++ supports a special constructor member function such a situations. Syntax: Derived-constructor(args list) : base-constructor(arg1), base-constructor(arg2),... { // body of the derived // class constructor ... ... }
92

Templates: Template is a concept which enables us to define generic classes and functions and thus provides support for generic programming. Generic programming: It is an approach where generic types are used as parameters in algorithms so that they for a variety of suitable data types and data structures.

93

A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types. Similarly, we can define a template for a function, say sum(), that would help us create various versions of sum() for adding int, float and double data types. A template can be considered as a kind of macro. When an object of a specified type is defined for actual use, the template definition for that class is substituted with the required data type. Template can be called parameterized classes or functions.
94

Definition of class template: Template class<T> Class class_name { //data members and functions }

95

Normal function template: Declaration: template class <T> function_name() { //code }

96

Template with multiple parameters:


Template<class T1, class T2> Class class_name { class dec & def }

97

Function templates with more arguments:


Template<class T> ret_type fun_name(parameters of template type) { statement 1; statement 2; statement 3; }

98

Exception handling Errors logical errors syntactic errors

Logical errors occur due to poor understanding of the problem and solution procedure. Syntactic errors occur due to poor understanding of the language itself. Other than these two, we come across peculiar problems which are called exceptions. These are runtime anomalies like division by zero, access to an array outside of its bounds, running out of disk space etc.,
99

Exception handling allows us to manage runtime errors in an orderly fashion. Using exception handling, our program can automatically invoke an error-handling routine when an error occurs.

100

C++ exception handling is built upon three keywords: try, catch, and throw. In the most general terms, program statements that we want to monitor for exceptions are contained in a try block. If an exception (i.e., an error) occurs within the try block, it is thrown (using throw). The exception is caught, using catch, and processed.

try Detects and throws block


Exception object an exception

catch Detects and throws block


an exception
101

The general form of try, throw and catch:

try {
... throw exception . } catch (type arg) { // catch block }

When the try block throws an exception, the program control leaves the try block and enters the catch statement of the catch block. Exceptions are objects used to transmit information about a problem.

102

Function invoked by try block throwing exception throw Function that causes point
an exception

Invoke function
Throw Exception

try Invokes a function that block


contains exception

catch Catches and handles block


the exception
103

Multiple catch statements: We can also define multiple catch blocks, in try blocks. Such program also contain multiple throw statements based on certain conditions. try { //try block } catch(type1 arg) { //catch block1 } catch(type2 arg) { //catch block 2} ::::::::::::::::::::: catch(typeN arg) {//catch block N}
104

As soon as the an exception is thrown, the compiler searches for appropriate match by matching catch() block. The matching catch() block is executed and control passes to the successive statement after the last catch() block. In case no match is found, the program terminates. In multiple catch() statement, if objects of many catch statements are similar to type of an exception, in such a situation the first catch () block that matches is executed.

105

Catching all Exceptions: In some situations, we may not be able to anticipate all possible types of exceptions and therefore may not be able to design independent catch handlers to catch them. In such situations, we can force a catch statement to catch all exceptions instead of a certain type alone. This can be achieved by defining the catch statement using ellipses. catch() { //all exceptions } Note: catch() should always be placed last in the list of handlers.
106

This pointer: If p is an object of class sample and get() is a member function of sample, the statement p.get() us used to call that function. The statement p.get() operates on p. in the same way if ptr is a pointer to p object, the function called ptr -> get() operates on *ptr. C++ compiler provides get() with a pointer to p called this. The pointer this is transferred as an unseen parameter in all calls to non-static member functions. The key word this is a local variable that is always present in the body of any non-static member function.
107

Operators new and new[] In order to request dynamic memory we use the operator new. new is followed by a data type specifier. If a sequence of more than one element is required- the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is: pointer = new type pointer = new type [no_of_elements] The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements.
108

Operator delete and delete[] Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is: delete pointer; delete [] pointer; The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements.
109

Advantages of new over malloc(): 1. It automatically computes the size of the data object. We need not use the operator sizeof. 2. It automatically returns the correct pointer type, so that there is not need to use a type cast. 3. It is possible to initialize the object while creating the memory space. 4. Like any other operator, new and delete can be overloaded.

110

Dynamic constructors: The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is called dynamic construction of objects.

111

Virtual functions: Virtual functions of base classes must be redefined in the derived classes. The programmer can define a virtual function in a base class and can use the same function name in any derived class, even if the number and type of arguments are matching. The matching function overrides the base class function of the same name. virtual functions can only be member functions.

112

Rules for Virtual functions: 1. The virtual function should not be static and must be a member class. 2. A virtual function may be declared as friend for another class. 3. Constructors can not be declared as virtual, but destructors can be. 4. The virtual function must be defined in public section of the class. 5. The prototype of virtual function in base and derived classes should be exactly the same. In case of mismatch, the compiler neglects the virtual function mechanism and treats them as overloaded functions.
113

Pure virtual functions: A pure virtual function is a function declared in a base class that has no definition relative to the base class. In such cases, the compiler requires each derived class either define the function or redeclare it as a pure virtual function. A class containing pure virtual functions cannot be used to declare any objects of its own. Such classes are called abstract base classes. The main objective of an abstract base class is to provide some traits to the derived classes and to create a base pointer required for achieving run time polymorphism. Ex: Virtual void display() = 0;

114

Anda mungkin juga menyukai