Vous êtes sur la page 1sur 150

1

Object Oriented concept

Layout of the Training Program

Session 1 : 3rd Sep, 15.30 17.45


OOPS Concept, C++ Fundamentals, Statements

Session 2 : 4th Sep, 10.55 12.45


Pointers, Memory Management, Storage Class and Functions.

Session 3 : 4th Sep, 15.30 17.45 Session 4 : 5th Sep, 10.55 12.45 Session 5 : 5th Sep, 15.30 17.45 Session 6 : 6th Sep, 10.55 12.45 Session 7 : 6th Sep, 15.30 17.45
TEST Inheritance Polymorphism, Function Overloading, Operator Overloading, Virtual functions.

Classes and Objects

Exception Handling, Templates

Session 1 (03-SEP-02,15.30-7.45) OOPS Concept C++ Fundamentals Statements

The Origin Of C++


C++ is a Object Oriented Programming ( OOP ) Language invented by Bjarne Stroustrup in 1979 at Bell Laboratory.

OOP concept was developed in late 70s Simula67, Smalltalk, Lisp, Clu, Actor, Eiffel, Objective C

JAVA is another Object Oriented Programming Language.

Why C++ : Procedure Oriented Programming


Before the Advent of Object Oriented Programming, Procedure Programming Language ( Structured Programming ) was being used.
In the procedure oriented approach, the problem is viewed as a sequence of things to be done, such as reading, calculating and printing. A number of function is written to accomplish these tasks.

The primary focus is on functions.

Procedure Oriented Programming

Main Program

Function - 1

Function - 2

Function - 3

Function - 4

Function - 5

Procedure Oriented Programming


Very little attention is given to the data that are being used by various functions.
Important data item are placed as global so that they may be accessed by all the functions. But this can produce bug ( error ) in your program.

Summary of POP
Large programs are divided into smaller program known as functions.
Most of the function share global data. Data move openly around the system from function to function. Emphasis is on doing things. Employs top-down approach in program design.
9

Object Oriented Programming (OOP)


OOP treat data as a critical element in the program development and does not allow it to flow freely around the system.
Ties data more closely to the functions that operate on it and protects it from accidental modification from outside. Allows to decompose a problem into a number of objects and then builds data and functions around these objects. Programs are divided into objects.
10

Object-Oriented Concepts
Objects are the physical and conceptual things we find in the universe around us. Like a person, a place, a bank account etc.
Object Oriented means that we organize software as a collection of discrete objects that incorporate both data structure ( member variables ) and behavior ( Methods ). Object Oriented Programming is a programming style that captures the behavior of the real world in a way that hides detailed implementation.

11

Object-Oriented Concepts
What is Class?
A Class is a user defined data type that defines member variables and the member functions common to all objects of a certain kind.

A class contains variables and methods. The values of the variable define the state of the object and the methods define the behavior of the object.
Member Function (Methods) Member Variables (Variables) Object is an instance of class.

12

Object-Oriented Concepts

13

Object-Oriented Concepts

14

Object-Oriented Concepts
Need for classes
Classes are needed to represent real-world entities (objects) that are not only have data type properties (their characteristics) but also associated operations (their behavior).

15

Object-Oriented Concepts
Object Oriented Paradigms:
There are four main object oriented principles which are important to an overall object oriented approach.

Encapsulation Abstraction Inheritance Polymorphism

16

Object-Oriented Concepts
Encapsulation
The wrapping up of data and functions (that operated on the data) into a single unit (called class) is known as encapsulation. Also known as Data Hiding. The data is not accessible to the outside world and only those functions which are wrapped into the class can access it.

17

Object-Oriented Concepts
Abstraction
This is a process of design which allows us to ignore details. Abstraction allows question such as What can it do? rather than How is it going to do?

18

Object-Oriented Concepts
Example:
Class LightSource { Public : LightSource(); Void TurnOn(); Void TurnOff(); }

19

Object-Oriented Concepts
Inheritance

Inheritance is the process by which objects of one class can acquire the properties of objects of another class.

20

Object-Oriented Concepts

21

Object-Oriented Concepts
Inheritance and Reuse
C++ supports the idea of reuse through inheritance. A new type can be declared, which is an extension of an existing type. This new subclass is said to derive from the existing type, and is sometimes called a derived type.

22

Object-Oriented Concepts
Polymorphism
In Object oriented programming, polymorphism ( from the Greek meaning having multiple forms) is the characteristic of being able to assign different meaning to something in different contexts specifically, to allow an entity such as a variable, a function or an object to have more than one form. There are several different kinds of polymorphism.

23

Object Oriented Concepts


Some of the feature of OOP are:
Emphasis is on data rather than procedure. Programs are divided into objects. Functions that operate on the data of an object are tied together. Data is hidden and can not be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be added easily whenever necessary. Follows bottom-up approach in the program design.

24

Object-Oriented Concepts
Benefits of OOP:
Through inheritance, we can eliminate redundant code and extends the use of existing class. The principal of data hiding helps the programmer to build secure programs. It is easy to partition the work in a project based on objects. Object oriented systems can be easily upgraded from small to large systems. Software complexity can be easily managed.

25

C++ Fundamentals
C++, a superset of C, extends C by incorporating objectoriented features.

C++ programs differs from the C program in other ways also, including how I/O is performed and what headers are included.

26

C++ Fundamentals
A Simple C++ Program: Average of Two numbers
#include <iostream.h> int main() { float number1, number2, sum, average; cout << Enter Two numbers: ; cin >> number1; cin >> number2; sum = number1 + number2; // Sum the two numbers average = sum/2 ; cout << Average is: << average ; Return 0; }
27

C++ Fundamentals
Comments:
C++ introduces a new comment symbol ( // ). This is a single line comment. The C Style comment /*, */ are also valid.

Input Operator: cin >> number1;


cin and >> ( Extraction operator ) is used to get the input from the user.

Output Operator: cout >> Enter Two numbers: ;


cout and << ( insertion operator ) are used to display on the screen.

Cascading of I/O operators: cout << Average is: << average ;


The multiple use of << in one statement is called cascading. We can also cascade input operator >> also.

28

C++ Fundamentals
Basic Data Types in C++:
Type Typical Size in Bytes char 1 unsigned char 1 int 2 to 4 long 4 float 4 Double 8 * -2 ^ (n-1) to (2 ^ (n-1)) - 1 void is also a data type in C++. User Defined Data Types in C++:
Structures Classes Enum

Minimal range -128 to 127 * 0 to 255 -32768 to 32767 -2147483648 to 21472483647

29

C++ Fundamentals
Reference variables:
Reference variables provides an alias for a previously defined variable. A reference variable is created as follows: data-type& reference-name = variable-name; Ex. float x = 50; float& y = x; // y = 50 y = 100; // x = 100, y = 100

30

C++ Fundamentals
Manipulators:
These are the operators used to format the data display. The most common manipulators are endl and setw. The endl manipulator caused a linefeed to be inserted, when used in an output statement. The setw is used to specify a common field width for all numbers and force them to be printed right justified.

31

C++ Fundamentals
Type Casts Forces an expression to be specified type by using a cast.The general form of a cast is (type-name) expression // C notation Type_name (expression) // C++ notation

Ex. Average = sum / float(i) ;

32

C++ Selection Statement


The if Statement
The general form of if statement is if(expression) { statement; } else { statement; } Where a statement may consists of a sigle statement, a block of statement, or nothing. If expression evaluates to true ( anything other than 0 ), the statement that forms the target of if is evaluated, otherwise else part is executed. 33

C++ Selection Statement


If-else-if Ladder
If(expression) statement; else if(expression) statement else . . .else statement;

34

C++ Selection Statement


The (? :) Alternative
The (? :) Is called ternary operator because it requires three operands. Exp1 ? Exp2 : Exp3 Where Exp1,Exp2 and Exp3 are expressions. The value of a ? Expression is determined as follows: Exp1 is evaluated. If it is true , Exp2 is evaluated , else Exp3 is evaluated, and becomes the value of the expression.

35

C++ Selection Statement


switch Statement:
Test the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constants are executed. The General form of the switch statement is: switch(expression) { case constants1: stament; break; case constants2: statement; break; . . default: statement; 36 }

C++ Iteration Statements


Allows a set of instructions to be executed repeatedly until a certain condition is reached.
The for Loop:
The general form of the For statement is for(initialization;condition;increment) { statement; } Initialization is an assignment that is used to set the loop control. Condition is a relational expression that determines when the loop exits. The increment defines how the loop control variables changes each time loop is executed.

37

C++ Iteration Statements


The while Loop:
Its general form is while(condition) { Statement; } The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

38

C++ Iteration Statements


The do-while Loop:
Unlike for and while loops, which test the loop condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop. do-while loop always executes at least once. The general form of the do-while loop is do { statement; } while(condition);

39

C++ Jump Statements


The break statement:
Use it to force immediate termination of a loop, bypassing the normal loop conditional test.

When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

40

C++ Jump Statements


The continue statement:
It forces the next iteration of the loop to take place, skipping any code in between. For the while and do-while loops, program control passes to the conditional tests and for the for loop , continue causes the conditional test and increment portions of the loop to execute.

41

Session 2(04-SEP-02,10.55-12.45) Pointers Memory management Functions Storage Classes


42

Pointers
Pointers are variables that contains address, usually address of another variable.
Consider the declaration int i=3; i value

Location Name

6485

Address

43

Pointers
Consider int *ptr = &i;
&i gives the address of the variable i.

ptr will store the address of i.


*ptr gives the value at this address.

44

Pointers
Example
int main() { int i, *iVar; iVar = &i; *iVar = 10; cout <<*iVar = << *iVar <<i = << i ; }

45

Pointers

int main() {

int *iPtr, i=20; iPtr = &i; cout<<i before incrementing: << i << endl; *iPtr += 10; cout<<i after incrementing: << i << endl ;
}

46

Arrays & Pointers


Array name holds the address of the first element in that array. cStr 0X100 Example
char cStr[] = Hi;

0X104

0X101 0X102 0X103 0X104 0X105 0X106


47

cStr[0] cStr[1] cStr[2]

H i \0

Arrays & Pointers


char cStr[] = "CSC India"; int main() { char *cPtr, cVar='A'; cPtr = cStr; cout<< *cPtr << endl << cPtr <<endl; cPtr++; cout<< *cPtr << endl << cPtr << endl; cPtr = &cVar; cout << *cPtr; return 0; }
48

Memory Management
Provides two dynamics allocation operators:
new To allocate the memory at run time delete free memory at run time. The general form of the new operator is: type *var = new type[size] Where type is the datatype of the variable, for which you are going to allocate the memory. Var is the variable name which will hold that much of memory. Size is the amount of memory to hold a variable.

Ex. int* pInt = new int[4] pInt will hold memory to have four interger variables.

49

Memory Management
The general form of the delete operator is:
delete var This will delete memory hoded by the var. Use delete [ ] var , if you are using new type[ ] . Use delete var , if you are using new type.

50

Memory Management
Advantage of new over malloc:
1. Automatically computes the size of the data object. We need not use the operator sizeof. 2. Automatically returns the correct pointer type, so no need to use a type cast. 3. It is possible to initialize the object while creating the memory space. Ex. int* p = new int(10); 4. new and delete can be overloaded.
51

Functions
Functions are used to divide your large program into smaller parts and is the major principles of top-down, structured programming.

In C++, the main() returns a value of type int to the operating system.

A function, that have a return value should use the return statement for termination.

52

Functions
The general form to create a Function is:
ret-type function_name(argument-list) { Body of the function } ret_type specifies the type of data that the function returns. A function may return any type of data except an array. argument-list is a comma separated list of variables names and their associated types that receives the values of the arguments when the function is called.

Example float volume(float length, float width, float height);

53

Functions

To define a function, just add its body: int sum(int a, int b) {


int mysum; mysum = a + b ; cout << Sum of the two numbers is: << mysum << endl; return mysum;
}

54

Functions
Calling a function
A function can be called in two ways in C++: Call by value Call by reference

55

Functions
Call by Value
When an argument is passed call by value, a copy of the arguments value is made and passed to the called function i.e original variable is never passed to the function. Changes to the copy do not affect the original variables value in the caller. This prevents the accidental side affect that so greatly hinder the development of correct and reliable software system. One disadvantage of call by value is that if a large data item is being passed copying that data can take a considerable amount of execution time.
56

Functions
Example: Call by Value
int main() { int i = 5; i = mynumber(i); cout << My number is: << i << endl ; return 0; } int mynumber(int i) { i = i + 1; Return i; }

57

Functions
Call by reference
Call by reference can be done by two ways either using reference arguments or with pointer arguments.

When calling a function with arguments that should be modified, the addresses of the arguments are passed. This is normally accomplished by applying the address operator (&) to the name of the variable whose value will be modified.

58

Functions
Example : Call by Reference
int main() { int mynumber(int& i); // function declaration int i = 5; i = mynumber(i); cout << "My number is: " << i << endl ; return 0; } int mynumber(int &i) { i = i + 1; return i; }
59

Functions
Example : Through Pointers
int main() { int mynumber(int* i); // function declaration int i = 5; i = mynumber(&i); cout << "My number is: " << i << endl ; return 0; } int mynumber(int* i) { *i = *i + 1; return *i; }
60

Functions
inline functions:
To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.

An inline function is a function that is expanded inline, when it is invoked.


Example

inline double cube(double a) { return (a*a*a); }


61

Functions

inline keyword is merely a request, not a command, to the compiler. Using inline functions can reduce execution time but increase program size inline expansion may not occur in following situations Functions containing static variables Recursive functions Functions containing loop, switch, go to statements.
62

Storage Classes
A variables storage class determines the period during which that variable exists in memory. Some variable exist briefly, some are repeatedly created and destroyed and others exist for the entire execution of a program.

An variables scope is where the variable can be referenced in a program.

63

Storage Classes
Four Types of Storage Classes
1. 2. 3. 4. Auto register static extern

The general form is: storage-specifier type var-name;

64

Storage Classes
Auto
A functions local variables and parameters normally are of automatic storage class.

Scope : Function in which it is declared Lifetime : Into the function only Default value : Garbage
E.g.. auto double x,y; Local variables are of automatic storage class by default, so keyword auto is rarely used.
65

Storage Classes

Register
The storage class specified register can be placed before an automatic variable declaration to suggest that the compiler maintain the variable in one of the computers high performance speed hardware register rather than in the memory.
Scope : Function in which it is declared Lifetime : Into the function only Default value: Garbage value

It is used for intensely used variables such as counters or totals can be maintained in hardware registers. E.g. register int counter = 1;
The compiler might ignore register declarations.
66

Storage Classes
Extern
Used to tell all the files about the global variables required by program. Scope: in whole the program, Exist from the point it is declared. Lifetime whole the program Default value 0 ( Zero) For variables, storage is allocated and initialized once when the program begins execution. Global variables and function names are its examples.

67

Storage Classes
File One int x,y; char ch; int main() { }
void func() {
x = 123;

File Two extern int x,y; extern char ch; int main() { }
void nextfunc() {
y = 10;

}
68

Storage Classes
Static
Static variables are permanent variables with in their own function or file. Scope: Within the function or file where declared Lifetime: Whole the program Default value: 0( Zero )

Static Local Variable


When you apply the static modifier to a local variable, the compiler creates permanent storage for it, much as it creates storage for a global variable.

Static Global Variable


Applying specifier to a global variable instructs the compiler to create a global variable that is only to the file in which it is declared it.
69

Session 3(04-SEP-02,15.30-17.45) Classes and Objects

70

Classes and Objects

A Class is used to create User defined data types.


A class will hold variables, which are called data members and method which are called member functions. Member functions are sometimes called Messages also. Member functions are used to operates on the member variables. A class is a way to bind the data and its associated functions together. It allows the data to be hidden from external use. Class is similar to Structure in C, except that variables and functions declared in class is Private by default, whereas in structure they are Public by default.
71

Classes and Objects


The general form the class declaration is:
class class_name { private: Private data and functions; public: Public data and functions; protected: protected data and functions. };

72

Classes and Objects


The private access specifier can be accessed only by other member of the class.
The public access specifier allows functions or data to be accessible to other parts of the program. The protected access specifier is only needed when inheritance is involved. You can not initialize non-static member variables.

73

Classes and Objects


Ex. of a class:
class stack { private: int stck[10]; int tos; public: void push(int I); int pop(); };

74

Classes and Objects


The functions push() and pop() are called member functions and variables stck and tos are called member variables.
Creating Objects:
Once you have defined a class, you can create an object of that type by using the class name. Ex. stack mystack; // memory for mystack is created When you declare an object of a class, you are creating an instance of that class. You can create as many number of object as you required. Ex. stack mystack1, mystack2, mystack3

75

Classes and Objects


Defining Member Functions:
Once you have created a class, you should write some logical code for that function. Exvoid stack :: push(int I) { if(tos == 10) { cout << Stack is full << endl; return ; } stck[tos] = I; tos++; } The :: is called scope resolution operator, it tells the compiler that push() belongs to the stack class.
76

Classes and Objects


Accessing Member function of the Class:
You can refers the methods of the class by creating the object of that class. Ex. stack stack1; // creates the object of the stack class stack1.push(2); // calling push() member function.

Recall that the private members of an object are accessible only by functions that are the member of that object. Ex. stack1.tos = 0; // Error, tos is private.
77

Classes and Objects


Arrays within a Class:
The arrays can be used as member variables in a class. The following class definitin is valid: const int size = 10; class myclass { private: int a[size]; public: void setval(); void display(); };
78

Classes and Objects


Constructors :
A constructor function is a special function that is a member of a class and has the same name as that class. Constructor function does not have a return type. Constructors are used to give initial value to the member variables i.e to initialize the object, when they are first created. Constructor without any argument is called default constructor.
79

Classes and Objects


When you are not written a constructor in your class then a do nothing version of a default constructor is invoked.
You can overload a constructor. When you are having overloaded constructor, then you should supply a default constructor. An objects constructor is automatically called when the object is created.

80

Classes and Objects


Destructors:
This is a special function which is called when the object is destroyed. Destructor is used to cleanup the things. Destructor has the same name as constructor, but it is preceded by a ~. Destructors, also dont have any return type. You can not overload a Destructor function.
81

Classes and Objects


Stack ex. : class stack
{ Private: int stck[10]; int tos; Public: Stack(); // constructor ~stack(); // destructor void push(int I); // push a number on the top of the stack int pop(); // Get a number from the top of the stack; };
82

Classes and Objects

Constructor Definition:
Stack::stack() { tos = 0; cout << Stack initialized << endl; }

Destructor Definition:
Stack::~stack() { cout << Stack destroyed<< endl; }
83

Classes and Objects


Parameterized Constructors:
When you pass arguments to the constructor, it is called parameterized constructor. These arguments help initialize an object when it is created.

84

Classes and Objects


Copy Constructors:
Copy constructor is used to initialize an object with an already created object.

The most common general form of a copy constructor is: classname(const classname& ob) { // body of the constructor } where ob is a reference to the object on the right side of the initialization.
85

Classes and Objects


copy constructor is invoked like :
myclass ob1; . . // do something with ob1 object . myclass ob2 = ob1; // calls the copy constructor myclass ob3(ob2); // again example of copy constructor

copy constructor is also called when you pass arguments in a function or return value from a function as a call by value.

Defining a copy constructor can help you prevent problems that might occur when one object is used to initialize others.
86

Classes and Objects


Static Class Members:
Both Data and function of a class can be made static. Static Data Members: It is initialized to zero when the first object of its class is created. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Ex. class myclass { static int i; // declaring static variable }; int myclass :: i; // defining static variable
87

Classes and Objects


Usage of static variables:
Provide access control to some shared resource used by all the objects of a class. To keep track of the number of objects of a particular type that are in existence. Eliminate any need of the global variables.

88

Classes and Objects


Static Member Functions:
Static member functions can have access to only other static members(function or variables) of the class. A static member function can be called using the class name ( instead of its objects) as follows: class-name :: function-name; There can not be static and no static version of the same function. They can not be declared as a const. Ex. Myclass ob1; MyClass :: MyStaticFunction();
89

Classes and Objects


Const Member functions:
Used to apply on a class, which does not alter any data in the class. Ex. int mul(int, int ) const; double getbalance() const;

90

Classes and Objects


Objects as Function Arguments:
Like many other data type, an object can be used as a function argument. Can be done in the following ways: A copy of the entire object is passed to the function ( pass by value ). Only the address of the object is transferred to the function ( pass by reference ). An object can also be passed as an arument to a non-member function.

91

Classes and Objects


Returning Objects:
Functions can not only receive objects as arguments but also can return them. Ex. Complex sum(complex c1, complex c2);

92

Classes and Objects


Friend Functions:
It is used to grant a non member function access to the private members of a class by using a friend keyword. A Friend function has access to all private and protected members of the class for which it is used. Ex. class myclass { int a, b; public: friend int sum(myclass x); void set_ab(int i, int j); }
93

Classes and Objects


void myclass :: set_ab(int i, int j) {
a = i; b=j;

} int sum(myclass x) {
return x.a + x.b ;

94

Classes and Objects

Friend functions are not a member of class. So they are called just as a plain function.
myclass ob; ob.set_ab(2,3); cout << sum(ob);

95

Classes and Objects


Member function of one class can be friend function of another class. In such case, they are defined using scope resolution operator.
class X { int fun1(); }; class Y { friend int X :: fun1(); };
96

Classes and Objects


Friend Class:
You can declare whole class as a friend into another class. When a class ( say myclass1 ) is declared friend into another class ( say myclass2), then methods of myclass1 have access to the private members of the myclass2. class Z { friend class X; };

97

Classes and Objects


The this pointer:
Used to represent an object that invokes a member function. It is a pointer that points to the object for which this function was called. Automatically passed to a member function when it is called I.e it acts as an implicit argument to all the member functions.

98

Session 4(05-SEP-02,10.55-12.45) Inheritance

99

Inheritance
Inheritance is to support the concept of reusability in C++. The Mechanism of deriving a new class from an old one is called Inheritance.

The Old class is called base class( Parent Class ) and the new one is called the derived class (Child Class) .
A class can inherit properties from more than one class. A derived class with only one base class is called single inheritance and one with several base classes is called multiple inheritance.
100

Inheritance
Defining Derived Classes:

class derived-class-name : visibility-mode base-class-name { // members of the derived class. } Ex. class ABC : private XYZ
{
// members of ABC class. }
101

Inheritance
When a base class is privately inherited by a derived class, public members of the base class becomes private members of the derived class.
When a base class is publicly inherited by a derived class, public members of the base class become public members of the derived class. In both the cases, the private members are not inherited. Base class member can be overridden by defining a derived class member with the same name as that of base class member. To access base class member from a derived class, the scope resolution operator may be used.
102

Inheritance
Different forms of Inheritance
1. Single inheritance 2. Multiple inherence 3. Hierarchical inheritance 4. Multilevel inheritance

Single Inheritance
When a subclass inherits only from one base class, it is known as single inheritance.
103

Inheritance

104

Inheritance
Making a private member inheritable:
protected is used for this purpose. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. Can not be accessed by the functions outside these two classes. When a protected member is inherited in public mode, it becomes protected in the derived class too. If it is inherited in private mode, becomes private in the derived class.

105

Inheritance

Multi Level Inheritance


When a subclass inherits from a class that itself inherits from another class, it is called as multilevel inheritance.

106

Inheritance

107

Inheritance

Hierarchal Inheritance
When many subclasses inherit from a single base class, it is known as hierarchical inheritance.

108

Inheritance

109

Inheritance

Multiple Inheritance
When a subclass inherits from multiple base classes, it is known as multiple inheritance.

110

Inheritance

111

Inheritance
Subclass inherits properties from multiple base classes. Syntax:
class derived: visibilty base1, visibilty base2 { // }

Multiple Inheritance occurs when a class inherits from more than one parent

112

Inheritance
Example:
class M { protected: int m; public: void get_m(int x); }; class N { protected: int n; public: void get_n(int y); }; void M :: get_m(int x) { m = x; } void N :: get_n(int y) { n = y; } void P :: display() { cout << "m = " << m << endl; cout << "n = " << n << endl; cout << "m*n = " << m * n << endl; } int main() { Pp; p.get_m(10); p.get_n(20); p.display(); return 0; }

class P : public M, public N { public: void display(); };

113

Inheritance

114

Inheritance
Ambiguities in Multiple Inheritance
int Avar

int Cvar int Bvar

D
int Dvar
115

Inheritance

void main() { D Dtemp; Dtemp.Avar=10; //Ambiguous Dtemp.B::Avar=10; //OK }

This is one way to resolve ambiguity

116

Inheritance
Virtual Base Class
To avoid ambiguity, modify class definitions as below:

class A{}; class B:virtual public A {}; class C:virtual public A {}; class D:public B, public C {};

117

Inheritance
Constructors in Derived Classes:
If a base class has a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors. Base class constructor is executed first and then derived class constructor. In case of multiple inheritance, the base classes are constructed in order in which they are declared in the derived class declaration.
118

Inheritance
The general form of defining a derived constructor is:
derived-constructor(arglist1,arglist2, , arglistN, arglistD) : base1(arglist1), base2(arglist2), . . . baseN(arglistN) { Body of the derived class }

119

Inheritance
destructors are executed in the reverse order of the Constructor.

120

class alpha { int x; public: alpha(int i) { x=i; cout << "alpha initialized" << endl; } void show_x() { cout << "x = " << x << endl; } }; class beta { int y; public: beta(int j) { y = j; cout << "beta initialized " << endl; } void show_y() { cout << "y = " << y << endl; } };

class gamma : public alpha, public beta { int m, n ; public: gamma(int a, int b, int c, int d) : alpha(a), beta(b) { m = c; n = d; cout << "gamma initilized" << endl; } void show_mn() { cout << "m = " << m << endl << "n = " << n << endl; } }; int main() { gamma g(5,10,15,20); g.show_x(); g.show_y(); g.show_mn(); return 0; }

121

Inheritance
Nesting of Classes:
Another way of inheriting properties of one class into another. This type of relationshio is called containership or nesting. Ex. class alpha { }; class beta { }; class gamma { alpha a; beta b; };
122

Session 5(05-SEP-02,15.30-17.45) Polymorphism Function Overloading Operator Overloading Virtual Functions

123

Polymorphism
Polymorphism means many forms. Same message ( member function) sent to different objects would be processed in different ways. Two type of Polymorphism:
Compile Time Polymorphism Function Overloading Operator Overloading

Runtime Time polymorphism Virtual Functions

124

Polymorphism
Function Overloading
C++ enables several functions of the same name to be defined as long as these functions have different sets of parameters. This capability is called function overloading. When an overloaded function is called the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call.

125

Polymorphism

Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. Creating overloaded functions with identical parameter lists and different return types is a syntax error.

126

Polymorphism

Overloaded functions are distinguished by their signaturesa signature is a combination of a functions name and its parameter types.

127

Polymorphism

Example
int square (int x) {return x * x; } Double square (double y) {return y * y; } int main() { cout<<Square of int 7 is <<square(7) <<\n Square of double 7.5 is <<square(7.5)<<endl; return 0; }

128

Polymorphism
Operator Overloading
Operator overloading contributes to C++s extensibility, one of the languages most appealing attributes. When an operator is overloaded, none of its original meaning lost. You can overload the operators by creating operator functions. An operator function is created using the keyword operator.

Operator functions can be either members or nonmembers ( friends ) of a class. Basic difference between them is that a friend function will have only one argument for unary operator and two for binary operator, while a member function has no argument for unary operator and only one for binary operators.
129

Polymorphism
Defining Operator Overloading:
ret-type class-name :: operator # (arg-list) { Function body } # is an place holder, substitute your operator in place of #. Ex. vector operator + ( vector ); // vector addition friend vector operator + ( vector , vector ); vector operator (); // unary minus friend vector operator (vector );
130

Polymorphism
Invoking overloaded operator functions:
For Unary Operator: op x or x op ( where op = operator , x = object )

For Binary Operator : x op y ( x and y are object of same class,op =operator )

131

Polymorphism
Examples: Through Member Function
String& operator + ( const String& s) {

char* temp; temp = new char[strlen(str) + strlen(s.str) + 1];


temp = strcat(str,s.str); return String(temp);
} int main(): String s1("CSC"); String s2(" India"); s1 = s1 + s2; // will print CSC India
132

Polymorphism
Examples: Through Friend Function
friend String& operator + ( String s1, String s2) { char* temp; temp = new char[strlen(s1.str) + strlen(s2.str) + 1]; temp = strcat(s1.str ,s2.str ); return String(temp); } In Main(): String s1("CSC"); String s2(" India"); s1 = s1 + s2; // will print CSC India
133

Polymorphism
We can overload all the C++ operator except the following:
Scope Resolution Operator ( :: ) Size Operator ( sizeof() ) Conditional Operator ( ? : ) Class Member Access Operator (., .*)

134

Polymorphism
Virtual Functions:
Virtual functions are member functions, that is declared in base class and redifined by a derived class. The redefinition of a virtual function in a derived class is usually called overriding. To create a virtual function, precede the function declaration by keyword virtual. Virtual functions are used to achieve the Run time polymorphism.

135

Polymorphism
A base class pointer can be used to point to an object of any class derived from the base.
When a base pointer points to a derived object that contains a virtual function, C++ determines which version of that function is called function is called based upon the type of object pointed to by the pointer.

136

Polymorphism
class shape { public: virtual void display() { cout << "In the shape class " << endl;} }; class circle : public shape { public: void display() };

{ cout << "In the circle class" << endl;}

class triangle : public shape { public: void display() { cout << "In the triangle class" << endl; } };

int main(int argc, char* argv[]) { shape* pSh = new shape; pSh->display(); pSh = new circle; pSh->display(); pSh = new triangle; pSh->display(); return 0;

137

Polymorphism
Pure Virtual Functions:
This is a function that is declared in the base class that has no definition relative to the base class. Pure virtual function are declared like below: virtual void display() = 0; Each derived class to either define the function or redeclare it as a pure virtual functions. Abstract Class: A class containing at least one pure virtual function can not be used to declare any objects of its own.

138

Session 6(06-SEP-02,10.55-12.45) Exception Handling Templates

139

Exception Handling
Exception Handling allows you to manage run time errors.
Exception Handling is built upon three keywords:
try catch throw

Program statements that you want to monitor for exceptions are contained in a try block. If an exception occurs within the try block, it is thrown using the throw. The exception is caught using the catch and processes.
140

Exception Handling
The General form of try and catch is:
try { // statements } catch(type1 arg) { // catch block } catch(type2 arg) { } . . Catch(typeN arg) { }

141

Exception Handling
When an exception is thrown, it is caught by its corresponding catch statement. Which catch statement is executed is determined by the data type of the exception.
throw statement:
throw exception throw generates the exception specified by exception. If you throw an exception for which there is no applicable catch statement,an abnormal program termination may occur.

142

Exception Handling
Using Multiple catch Statement Example:
void test(int i) { try { if(i) throw i; else throw "value is zero"; } catch(int num) { cout << "Caught exception number: " << num << endl; } catch(char* str) { cout << "Caught exception string: " << str << endl; } } int main() { test(1); test(2); test(0); test(3);

// Caught exception number: 1 // Caught exception number: 2 // Caught exception string: value is zero // Caught exception number: 3

143

Exception Handling
Catching All Exception:
Use this form of catch catch() { // stmt } Use of this form is write it as the last catch of a cluster of catches.

144

Templates

Templates are used to create generic functions and classes. You can use one function or class with several different types of data without having to explicitly recode specific versions for each data type. These cab be created with template keyword.

145

Templates
Generic Functions:
By creating a generic function, you can define the nature of the algorithm, independent of any data. The general form of a template function definition is: template<class T> ret-type func-name(parameter list) { body of the function }

146

Templates
Example:
template<class T> T summation(T a, T b) { return a + b; } int main() { cout << "Summation of two integer is: " << summation(2,3) << endl; cout << "Summation of two float is: " << summation(2.2,3.3) << endl; return 0; }

147

Templates
Generic Classes:
Generic classes are useful when a class uses logic that can be generalized. Ex. The same algorithm that will maintain a queue of integers will also work for a queue of characters. The compiler will automatically generate the correct type of object, based upon the type you specify when the object is created.

148

Templates
The general form of the class decaration is:
Template<class T> Class class-name { . . . };

The general form to create object of the class is:


class-name<T> ob;

149

Templates
template<class T> class Stack { private: T stck[10]; int tos; public: Stack() { tos = 0 ;}; void push(T num); T pop(); };
template<class T> void Stack<T> :: push(T num) { if(tos == 10) { cout << "Stack is full" << endl; return; } else { stck[tos] = num; tos++; } }

template<class T> T Stack<T> :: pop() { if(tos == 0) { cout << "Stack is empty" << endl; return 0; } else { tos--; return stck[tos]; } }

int main() { Stack<int> oInt>; oInt.push(10); oInt.push(20); oInt.pop(); oInt.pop(); Stack<char> oChr; oChr.push(a); oChr.push(c); oChr.pop(); oChr.pop();

// stack of integer

return 0; }

150

Vous aimerez peut-être aussi