Vous êtes sur la page 1sur 11

CP Module4 Notes-2 (In addition to the class note)

Applications of Scope Resolution Operator ( :: ) in C++ It resolves a dispute in scope when local and global variables exist with the same name. For example, if we have local and global variables with the same name a, then a refers to the local variable a and ::a refers to global variable a. (Its order of evaluation is from Right to Left) One of the objectives of OOP is to separate the implementation details from the class definition. If in a class we have only prototype of a function and if it is defined out side the class, then we define it as return-type class-name :: function-name( arguments) { function body } (Here the order of evaluation is from Left to Right ) Inline Functions During a function execution, some time will be spent for transferring control to the function module, performing a set of statements, and again transferring the control( returning) to the place from where it is called. To eliminate this wastage of time, C++ provides a new feature known as Inline Function. An inline function is a function which is expanded in line( on the same line) when it is called. ie, the compiler replaces the function call with the corresponding function code. Its syntax is inline return-type function-name(arguments) { function body } eg: inline int square( int a) { return a*a; } To make a function inline, only we need to use the key word inline just before the function definition. inline function =>more space wastage & less execution time ordinary(normal)function => more execution time & less memory wastage. Even if we declare a function to be inline, there is no guarantee that the C++ compiler will treat it as an inline function. If it has more number of statements, then it will be taken as a normal function . Similarities between macros and inline functions Inline functions are similar to # define macros. Both results in more space wastage. Both results in less execution time. Differences between macros and inline functions Inline functions do not have side effects associated with macros. (Refer the following example ) #define SQUARE(x) x*x // This is a macro. inline int square(int y) // This is an inline function. { return y*y; } void main( )
1

{int a=2,b=2,c,d; c=SQUARE(++a);// Here a is incremented 2 times before squaring even though we have used ++only once ; c=16 d=square(++b); //Here a is incremented only once before squaring. d=9 cout<<c=<<c<<endl<<d=<<d; } (1)Write a program in C++ to overload + operator to concatenate two strings. #include<iostream.h> #include<string.h> class string { private :char a[100]; public :void input() { cin>>a; } void output() { cout<<a; } string operator +(string s2) { string s3; strcpy(s3.a,a); strcat(s3.a,s2.a); return s3; } }; void main() { string s1,s2,s3; s1.input(); s2.input(); s3=s1+s2; //s1.+(s2) s3.output(); } Visibility Lables ( Visibility mode specifiers) The following table shows the visibility of members of a class. Visibility Meaning private members Visible to member functions within its class. protected Visible to member functions of its own class and its derived class.[ A members protected member can not be accessed from functions outside these classes, such as main( ).] public members Visible to all functions in the program.[including main( )]

INHERITANCE Reusability is an important feature of OOP, which is strongly supported by C++. Once a class has been written and tested, it can be adapted by other programmers to suit their requirements. The mechanism of deriving a new class from an old one is called Inheritance.(or derivation). The old class is known as the base class and the new one is called the derived class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one base class, is called Single Inheritance and one with several base classes is called Multiple Inheritance. If the properties of one class are inherited by more than one class, the inheritance is said to be Hierarchical Inheritance. The mechanism of deriving a class from another derived class is known as multilevel inheritance. The combination of two or more types of inheritance is known as hybrid inheritance. 1.Single Inheritance 2.Multiple Inheritance Base class
A A B

Derived class

3.Multilevel Inheritance
A B

4. Hierarchical Inheritance
A

B C

C A

5.Hybrid Inheritance

D INHERITANCE (C++ programs) (1)./* TO ILLUSTRATE SINGLE INHERITANCE .File:NAVEEN/ MAYO1A.CPP...*/ #include<iostream.h> class B { private : int n; public : void input() { cout<<"Enter n"<<endl; cin>>n; 3

} int getn() { return n; } }; class D : public B (Read this as class D derives from class B and the inheritance is public { inheritance.) private : int x; public : int square() { x=getn()*getn(); return x; } void display() { cout<<"n="<<getn()<<endl; cout<<"square of n="<<x<<endl; } Output }; Enter n void main() 12 { n=12 D d; square of n =144 d.input(); d.square(); d.display(); } (2.)/*TO ILLUSTRATE MULTILEVEL INHERITANCE .File:NAVEEN/MAYO1B.CPP...*/ #include<iostream.h> class B { private : int n; public : void input() { cout<<"Enter n"<<endl; cin>>n; } int getn() { return n; } }; class D : public B { private : int x; public : int square()
4

{ x=getn()*getn(); return x; } int getx() { return x; } }; class X : public D { public : void display() { cout<<"n="<<getn()<<endl; cout<<"square of n="<<getx()<<endl; } Output }; Enter n void main() 12 { n=12 X x; square of n =144 x.input(); x.square(); x.display(); } (3)./* TO ILLUSTRATE MULTIPLE INHERITANCE .File:NAVEEN/MAYO1C.CPP...*/ #include<iostream.h> class M { protected : int m; public : void getm(int x) { m=x; } }; class N { protected : int n; public : void getn(int y) { n=y; } }; class P: public M,public N { public : void display() {
5

Output }; m=10 void main() n=20 { m*n= 200 P p; p.getm(10); p.getn(20); p.display( ); } The program examples for Hierarchical Inheritance and Hybrid Inheritance are left as an exercise. Visibility of Inherited Members Derived class visibility public inheritance not inherited protected public private inheritance protected inheritance not inherited private private not inherited protected protected

cout<<"m="<<m<<endl; cout<<"n="<<n<<endl; cout<<"m * n ="<<m*n<<endl; }

Base class visibility (Visibility of members in the base class) private protected public

friend functions We have seen that only member functions of a class can access its private members. However, if two classes need to share a particular function, it is done with the help of friend functions. In these cases, C++ allows the common function to be made friendly with both the classes. Such functions are known as friend functions. Even though a friend function is not a member of a class, it has full access rights to the private members of the class just like its own member functions. Rules regarding friend functions It should not be in the scope of the classes to whom it is a friend function. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be declared either in the public or the private part of a class without affecting its meaning. Usually objects are passed as arguments. eg:#include<iostream.h> class sample { private : int a,b; public : void setvalue() { a=25;b=40; }
6

friend float mean (sample x); }; float mean(sample x) { return float (x . a + x .b)/2 ; } void main( ) Output { Mean value=32.5 sample x; x.setvalue( ); cout<<Mean value =<<mean(x); } Note :-Member function of one class can be a friend function of another class. eg :class X { -------int fn1(); // member function of X. -------}; class Y { --------friend int X :: fn1( ); //fn1( ) of class X is a friend of class Y. }; friend class If all the member functions of one class are the friend functions of another class, then the class is said to be a friend class. eg:class Z { ----------friend class X; // All member functions of X are friends to Z. }; POLYMORPHISM
Polymorphism

Compile time Polymorphism

Run time Polymorphism

Function overloading

Operator overloading

Virtual functions

Static Binding & Dynamic Binding Compile time polymorphism is also known as early binding or Static Binding or static linking. Run time polymorphism is also known as late binding or Dynamic Binding. C++ supports a mechanism known as virtual function to achieve run time polymorphism. At run time, when it is known what class objects are under consideration, the appropriate version of the function is invoked and hence it is known as Dynamic Binding. VIRTUAL FUNCTIONS Polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message, but in different forms. A single pointer variable can refer to the objects of different classes, inherited from the base class. A pointer to the base class may refer to the objects of different derived classes. Even though a base pointer is made to contain the address of a derived class object, it always executes the function in the base class. In this case,Polymorphism can be achieved using Virtual Functions. When we use the same function name in both the base class and the derived class, the function in the base class is declared as virtual, using the keyword virtual ,preceding its normal declaration. When a function is made virtu al, C++ determines which function to be used at run time, based on the type of the object pointed to by the base pointer. By making the base pointer to point to objects of different classes, we can execute different versions of the virtual functions. Note :- Virtual function is a function which acts as if it is not there in some occasions. /* Example to illustrate Virtual Functions */ #include<iostream.h> class base { public : void display() { cout<<"Display base"<<endl; } virtual void show() { cout<<"Show base"<<endl; } }; class derived : public base { public : void display() { cout<<"Display derived"<<endl; } void show() { cout<<"Show derived"<<endl; } }; void main()
8

{ base b; derived d; base *bp; cout<<"Base pointer points to the base"<<endl; bp=&b; Output bp->display(); //calls base version Base pointer points to the base bp->show(); //calls base version Display base cout<<"Base pointer points to the derived"<<endl; Show base Base pointer points to the derived bp=&d; Display base bp->display(); //calls base version Show derived bp->show(); //calls derived version } Pure Virtual Function A virtual function , equated to zero is called a pure virtual function. It is a function declared in the base class that has no definition relative to the base class. It is a do nothing function. A class containing such pure virtual functions is called an Abstract Class. Abstract class is an incomplete class. So we cannot create an object for that class. eg:#include<iostream.h> class colour { -----------public : virtual void display( ) =0; }; This class is an Abstract Class, and virtual void display( ) = 0 is a pure virtual function. Message Passing Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. A message for an object is a request for execution of a function and therefore will invoke a function in the receiving object that generates the desired result. Message Passing involves specifying the name of the object, the name of the function ( message) and the information to be sent. eg: employee. display (name); object message information

MEMORY MANAGEMENT OPERATORS new and delete operators in C++ new Memory allocation operator( Similar to malloc( ) and calloc( ) in C ) delete Memory release operator ( Similar to free( ) in C language ) C uses malloc( ) and calloc( ) functions to allocate memory dynamically (at run time), and free( ) to release the allocated memory which was done using malloc( ) or calloc( ). We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. C++ also supports two unary operators new and delete for dynamic memory allocation
9

and for deallocation of memory respectively, in a better way. These operators are also known as free store operators. An object can be created by using new and can be destroyed by using delete, as and when required. An object created by using new will remain in existence until it is destroyed by using delete. Syntax of new: pointer-variable =new data-type ; eg:- int *p; float *q; p=new int; OR int *p= new int; q=new float; OR float *q= new float; Syntax of delete : delete pointer-variable ; eg: delete p ; delete q; If sufficient memory is not available for allocation, new returns a null pointer like malloc( ) or calloc( ) does. Advantages of new over malloc( ) and calloc( ) It automatically computes the size of the data object. Hence no need of the sizeof operator. It automatically returns the correct pointer type, so that there is no need of type casting as we do in malloc( ) and calloc( ). Like any other operator, new and delete can be overloaded. TEMPLATES Template is used to define generic classes or generic functions. Template is a mechanism that makes it possible to use one function or class to handle different data types. By using a template, we can design a single function/class that operates on data of many types, instead of having to create a separate function/class for each type. When used with functions, they are known as function templates and when used with classes, they are called class templates. A class generated from a class template is called a template class. Similarly a function generated from a function template is called a template function. Function Templates Syntax : template < class T > T function-name( T argument1, T argument2,, T argument n) { ----------------} eg:- template < class T> T min (T a, T b) { return (a< b) ? a: b; } Class Templates Syntax : template < class T> class class-name {----------};
10

C++ program (example) for a function template #include<iostream.h> template <class T> T min( T a,T b) { if(a<b) return a; else return b; } void main() { int i=10,j=20; Output cout<<endl<<min(i,j); 10 float a=3.14,b=2.5; 2.5 cout<<endl<<min(a,b); A char ch='A',dh='Z'; cout<<endl<<min(ch,dh); } Exception Handling The two most common types of bugs are logical errors and syntactic errors. The logical errors occur due to poor understanding of the problem and the solution procedure. The syntactic errors occur due to poor understanding of the language. We can detect and correct these errors by the debugging and testing procedures. There are some errors which are other than logical or syntax errors. They are known as exceptions. Exceptions are run time errors or unusual conditions that a program may encounter while executing. They might include conditions such as division by zero, accessing an array outside of its bounds, or running out of memory or disk space. ANSI C++ provides built in language features to detect and handle exceptions.
Exceptions

Synchronous exceptions

Asynchronous exceptions

What we have explained here are examples of Synchronous Exceptions. Asynchronous exceptions are caused by events beyond the control of the program ( eg: key board interrupt). The exception handling mechanism in C++ is designed to handle only synchronous exceptions.
CP notes given by Naveen Balakrishnan

11

Vous aimerez peut-être aussi