Sunteți pe pagina 1din 125

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/1/2012 ATK.Prasanna kumar for SSi-Aptech SSi1

POP Approach Diagram


Main Program Function-1 Function-2 Function-3

Function-4 Function-6
1/1/2012

Function-5 Function-8
2

Function-7
ATK.Prasanna kumar for SSi-Aptech

In multi-function programming , many multiimportant data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. data. Global data Function-1 Local data
1/1/2012

Global data Function-2 Local data


ATK.Prasanna kumar for SSi-Aptech

Function-3 Local data


3

Drawbacks in POP Approach


Global data 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: Note: POP approach does not model real world problems very well, because functions are actionaction-oriented and do not really correspond to the elements of the problem.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

ObjectObject-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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

OOPs Approach Diagram Object A Object B Data


Communication

Data Functions Object C Functions Data

Functions

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

History
C++ is an object-oriented extension of C objectC was designed by Dennis Ritchie at Bell Labs  used to write Unix, based on BCPL C++ designed by Bjarne Stroustrup at Bell Labs  Called C with classes in early 1980 s  Popularity increased in late 1980 s and early 1990 s.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

Basic 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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 9

Commonly available objects

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 11

Y
Actions:
1/1/2012

Class : Properties:

Bus company, model, color, capacity

Actions: Class : Properties:

speed(), average()

computer brand, price, hard disk, RAM size processing speed(), display()
ATK.Prasanna kumar for SSi-Aptech 12

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 object s data and the program.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

13

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 14

4. Data Abstraction Abstraction refers to the act of representing essential features without including the background details. Class uses the concept of abstraction and is defined as a list of abstract attributes such as size, cost, height and a few functions to operate on these properties. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

15

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

16

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

17

7.Polymorphism: Polymorphism allows the same function to act differently in different classes.
Line Display()

Dotted objects

Display()
1/1/2012

stars Display()
ATK.Prasanna kumar for SSi-Aptech

Asterisk Display()
18

7. Dynamic binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not know until the time of the call at run time. Dynamic is associated with polymorphism and inheritance.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

19

C++ Program features: Comments: C++ uses a new comment symbol //. Comments start with a double slash symbol and terminate at the end of the line. The double slash comment is basically a single line comment. The C comments are more suitable for multiline comments.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

20

Output operator: The identifier cout is a predefined object that represents the standard output stream in C++. The operator << is called an insertion operator or put put to operator .

screen
cout
1/1/2012

<<

Hello
21

ATK.Prasanna kumar for SSi-Aptech

Input operator: The identifier cin is a predefined object that represents the standard input stream in C++. The operator >> is called an Extraction operator or put get from operator .
Keyboard

cin
1/1/2012

>>

25
22

ATK.Prasanna kumar for SSi-Aptech

C++ Data Types Derived Structure Union enumeration class


User defined

Built-in

Array Function Pointer reference

Integral type

void

Floating type float double

char

int

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

24

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

cin: Syntax: cin>>var1>>var2>> .>>varn;


1/1/2012 ATK.Prasanna kumar for SSi-Aptech 25

Frequently used unformatted input and output functions:


get()

cin

getline() read() put()

cout write()
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 26

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)
1/1/2012

cout.put(ch)
ATK.Prasanna kumar for SSi-Aptech 27

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);

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

28

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 29

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

30

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 31

Predefined manipulators: endl hex, dec, oct setbase setw setfill setprecision ws
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 32

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)
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 33

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.
ATK.Prasanna kumar for SSi-Aptech 34

4.

5.

1/1/2012

Flags: Format Left justification Right justification Fixed point notation Decimal base Octal base Hexadecimal base
1/1/2012

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


ATK.Prasanna kumar for SSi-Aptech

ios::hex

35

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);
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 36

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);

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

37

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);

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

38

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);

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

39

Some important keywords in c++:

catch friend operator public throw


1/1/2012

class inline private template try


ATK.Prasanna kumar for SSi-Aptech

delete new protected this virtual


40

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

41

Operators in C++: Operator << >> :: delete new &


1/1/2012

Description insertion operator extraction operator scope access (or resolution) operator memory release operator memory allocation operator referencing operator
ATK.Prasanna kumar for SSi-Aptech 42

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 43

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

44

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 45

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 46

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 47

The delete operator: Syntax: delete <pointer memory variable> delete[element size]<pointer mem_var> Ex: delete p; delete[5]p or delete[]p;

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

48

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 doesn t 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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

49

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 50

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> };
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

51

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

52

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 53

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

54

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

55

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 }
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 56

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 57

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 58

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech

59

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)

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

60

Memory allocation for object :


Common for all objects
Member function 1 Member function 2

Memory created when functions defined


Object 1 Object 2

Member variable1 Member variable2


1/1/2012

Member variable1 Member variable2


ATK.Prasanna kumar for SSi-Aptech 61

Memory created when objects defined

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 62

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 63

Object A

Object B

var1 var2 varn Static variable


Object C

var1 var2 varn

1/1/2012

var1 var2 varn


ATK.Prasanna kumar for SSi-Aptech

64

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

65

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) .
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 66

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

67

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 68

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);

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

69

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 70

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); };
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 71

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

72

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

73

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. It s name is same as the class name. A destructor is used to destroy the objects that have been created by a constructor. It s name is the same as class name but preceded by a tilde(~) operator.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 74

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 75

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

76

Copy constructor The constructor can accept arguments of any data type including user-defined data types and an object of its own class. statement(a) statement(b) class num class num { { private: private: .. public: public: num(num); num(num &); } }
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 77

In statement (a) an argument of the constructor is same as that of its class. Hence, this declaration is wrong. It is possible to pass reference of object of the constructor. Such declaration is known as copy constructor. The statement (b) is valid and can be used to copy constructor. when we pass an object by value into a function, a temporary copy of that object is created. All copy constructor require one argument, with reference to an object of that class. Using copy constructors, it is possible for the programmers to declare and initialize one object using reference of another object. Thus, whenever a constructor is called a copy of an object is created.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 78

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

79

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 80

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 81

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

82

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

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

83

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 84

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 85

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 86

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

87

When ++ and operators are overloaded, the system can t 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

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

88

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 89

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

90

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

91

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

92

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

93

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 94

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

95

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 96

Constructors in inheritance

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

97

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

98

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 99

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 ... ... }
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 100

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

101

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 102

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

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

103

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

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

104

Template with multiple parameters: Template<class T1, class T2> Class class_name { class dec & def }

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

105

Function templates with more arguments: Template<class T> ret_type fun_name(parameters of template type) { statement 1; statement 2; statement 3; }

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

106

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.,
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 107

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

108

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. Detects and throws an exception Exception object

try block

Detects and throws an exception


1/1/2012 ATK.Prasanna kumar for SSi-Aptech 109

catch block

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

110

Function invoked by try block throwing exception throw point


Function that causes an exception Invoke function Throw Exception Invokes a function that contains exception

try block

Catches and handles the exception


1/1/2012 ATK.Prasanna kumar for SSi-Aptech 111

catch block

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}
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 112

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

113

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 114

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 115

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 116

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 117

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

118

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

119

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.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

120

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.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 121

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;
1/1/2012

ATK.Prasanna kumar for SSi-Aptech

122

Dynamic polymorphism allows programmers to write code using functions applied to objects of the base class without worrying about how those functions will actually be defined by derived classes. For instance, programmers might call functions on a Shape object that computes its area or perimeter, without concerning themselves with the actual (derived) type of the object, whether it is a Rectangle, Square or Circle.

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

123

An essential requirement to take advantage of polymorphism in C++ is that there should be a way by which it is possible to refer to objects of derived classes using a pointer to a single type. This is possible by using a pointer to the base type, which can also point to derived class objects. Whenever a derived class redefines a function in the base class, the function needs to be declared virtual by prefixing the keyword virtual to the normal function declaration in the base class. This should be done if the programmer wishes to take advantage of run-time polymorphism.
1/1/2012 ATK.Prasanna kumar for SSi-Aptech 124

1/1/2012

ATK.Prasanna kumar for SSi-Aptech

125

S-ar putea să vă placă și