Está en la página 1de 44

BKR COLLEGE OF ENGINEERING DEPARTMENT OF CSE

CS 2203 OBJECT ORIENTED PROGRAMMING II YEAR III SEMESTER

LECTURE NOTES
CS 2203 OBJECT ORIENTED PROGRAMMING
UNIT I : Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions local classes INTRODUCTION

PROGRAMMING METHODOLOGIES *
The earliest computers were programmed in binary. Mechanical switches were used to load programs. With the advent of mass storage devices and larger and cheaper computer memories, the first high-level computer programming languages came into existence. These languages were simple to design and easy to use because programs at that time were primarily concerned with relatively simple tasks like calculations. They suffered from following limitations: No facilities to reuse existing program code. Control was transferred via the dangerous goto statement. All variables in the program were global. Tracking down spurious changes in global data was a very tedious job. Writing, understanding and maintaining long programs are very difficult.

Structured Programming: A structured program is built by breaking down the programs primary purpose into smaller pieces that then become functions within the program. Each function can have its own data and logic.

Information is passed between functions using parameters and functions can have local data that cannot be accessed outside the function scope. It helps you to write cleaner code and maintain control over each function. By isolating the processes within the functions, a structured program minimizes the chance that one procedure will affect another.

Main Program

Function 1

Function 2

Function 3

Function 4

Function 5

Limitations: Data is given second class status in the procedural paradigm even though data is the reason for programs existence. Data types are processed in many functions, and when changes occur in data types, modifications must be made at every location that acts on those data types within the program. Structured programming components functions and data structures doesnt model the real world very well. It emphasizes on fitting a problem to the procedural approach of a language.

Object oriented programming (OOP) concepts :


What is object oriented paradigm? (Nov/Dec2007)
Definition of OOP: It is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. OOP 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. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization of data and functions in object-oriented programs is shown in fig.1.1. The data of an object can be accessed only by the functions associated with that object. However functions of one object can access the functions of other objects. Object A Data Communication Member function Object C Member function Data Member Function Object B Data

fig. 1.1 Organization of data and functions in OOP *Comparison between Structured and Object Oriented Programming:

Structured Programming Emphasis is on doing things Large programs are divided into smaller programs known as functions Most of the functions share global data Data move openly around the system from function to function. Its components doesnt model the real world objects Employs top-down approach in program design.

Object Oriented programming Emphasis is on data Programs are divided into what are known as objects. Functions that operate on data of the object are tied together in the data structures Data is hidden and cannot be accessed by external function. Its components model the real world objects Follows bottom-up approach in program design.

*BASICS OF C++ ENVIRONMENT


C++ is an object oriented programming language. It was developed by Bjarne Strousturp at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980s. C++ is a superset of C. Every C++ program must have a main( ). Like C, the statements terminate with semicolons. File Extension: C++ programs have the file extension .CPP Comments: It introduces a new comment symbol // (double slash). This is basically single line comment. The C comment symbols are still valid in C++. E.g. // Welcome to PIT /* Welcome to PIT */ The iostream File: #include <iostream.h> The header file iostream.h should be included at the beginning of all the programs that use input/output statements. Output Operator: 5 C++ style C style

cout << Hello World; The identifier cout (pronounced as C Out) is a predefined object that represents the standard output stream (screen). The operator << is called the insertion or put to operator. Input Operator: cin >> variable; The identifier cin (pronounced C in) is a predefined object in C++ that corresponds to the standard input stream (keyboard). The operator >> is known as extraction or get from operator. Cascading of I/O Operators: The statement cout << Sum = << sum <<\n; first sends the string Sum = to cout and then sends the value of sum. Finally, it sends the newline character so that the next output will be in the new line. Similarly the input operator can be cascaded as follows: cin >> num1 >> num2; The values are assigned from left to right. That is if we type 27 and 13 then 27 will be assigned to num1 and 13 will be assigned to num2. Keywords: C++ has its own keywords in addition to the keywords in C. Some of them are catch class delete friend inline Identifiers: new operator private protected public template this throw try virtual

They refer to the name of the variables, functions, arrays, classes etc., created by the programmer. The rules for forming the variables are Only alphabetic characters, digits and underscores are permitted The name cannot start with the digit Uppercase and lowercase letters are distinct A declared keyword cannot be used as a variable name C++ allows the declaration of a variable anywhere in the scope. It makes the program easier to write and reduces the errors also makes the program easier to understand because the variables are declared in the context their use. Constants refer to the fixed values that do no change during the execution of a program. DATA TYPES:

What are different data types supported by C++? (April/May 2007)


User defined type structure union class enumeration Array Function Pointer Reference Integral type o int o char void Floating type o float 7

Derived Type:

Built in type

o double USER DEFINED DATA TYPES: STRUCTURE: Structure is a heterogeneous data structure which can store data elements of mixed data types.

SYNTAX: struct tagname { elements of structures; };


EXAMPLE:

struct emp { int roll; char name[40]; }; emp e,e1; In the above code a structure named emp is created with the following elements namely o rollno of integer data type o name of character array type. Then two structure variables are created namely e,e1. Using the structure variables e and e1 the members (elements) of the structure can be accessed. EXAMPLE e.roll=10; strcpy( e.name,ADAM); In structures all the elements of the structure are public by default.

Typecasting: If we carry out the operation between an int and float the int is promoted to a float before performing the operation. This conversion takes place automatically. As against this, data conversions can be carried out by the programmer explicitly. Two different types of typecasting are supported in C++. Example: int total = 450 , n = 7 float avg; avg = total / n; cout << average = << avg; Output: average = 64 After typecasting: int total = 450 , n = 7 float avg; avg = (float)total /n; // C style cout << average = << avg; Output: average = 64.29 C++ style: avg = float(total)/n; Operators in C++: :: ::* Scope resolution operator Pointer to member declarator 9

* .* delete endl new setw

Pointer to member operator Pointer to member operator Memory release operator Line feed operator Memory allocation operator Field width operator

Scope resolution Operator:

What is the use of the scope resolution operator : : in C++? (Nov/Dec2007)


Suppose there are two variables with the same name, one which is defined globally another is declared locally inside a function. If we attempt to access the variable a, we always access the local variable as the rule says, the local variable gets more priority over global variable. C++ provides a way to access the global variable using scope resolution operator. This scope resolution operator is used to define the function definition outside the class. Example: #include<iostream.h> int a = 27; void main() { int a = 13; cout << \nLocal value = << a << Global Value = << ::a ; ::a = 30; cout << \nLocal value = << a << Global Value = << ::a ; } Output: Local value = 13 Local value = 13 EXPRESSIONS: 10 Global Value = 27 Global Value = 30

Constant expressions Integral expressions Float expressions Pointer expressions Relational expressions Logical expressions Bitwise expressions.

The bool data type: This data type can take only two values true or false. It is most commonly used to hold the results of comparisons Example: bool x,y; int a = 10,b = 20, c = 30; x = a < b; y = b > c; // value of x = 1 // value of y = 0

1) Explain the following concepts of object oriented programming in detail with an example. (Nov/Dec2007) (i) (ii) (iii) (iv) 2) Explain Data abstraction Inheritance Polymorphism Objects. object-oriented paradigm with al1its essential elements'.

(April/May2008),(Nov/Dec2007) 3) What are the main characteristics of OOP language?(May/June 2007)

Basic concepts of OOP:


Objects Classes 11

Methods Message Passing Data Abstraction Encapsulation Inheritance Polymorphism Dynamic Binding Objects : Objects are the basic run-time entities in an object oriented programming. They may represent a person, a place, a bank account or any item that the program has to handle. They may represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and the nature of communication between them. Objects are the instances of the classes. When a program is executed, the objects interact by sending messages to another. Each object contains data and code to manipulate the data. Objects can interact without having to know the details of each others data or code. It is sufficient to know the type of message accepted, and the type of message accepted and the type of response returned by the objects. Fig. 1.2. Shows the representation of an object.

Object: STUDENT DATA: Name Roll No Mark 1, Mark 2, Mark 3 FUNCTIONS Total Average Display Data Members

Member Functions

Fig. 1.2. Notation of an object Classes: *Limitations of C structures: 12

The standard C doesnt allow the struct data type to be created like built-in types. They do not permit data hiding. Structure members can be directly accessed by the structure variables by any function anywhere in their scope. In simple words, the structure members are public members. *Extensions to structures: C++ supports all the features of structures as defined in C++. It treats the userdefined data type as close to built-in data type also it provides a facility to hide the data which is one of the main percepts of OOP. In C++, a structure can have both variables and functions as members. It can also declare some of its members as private so that they cannot be accessed directly by the external functions. In C++, the keyword struct can be omitted in the declaration of structure variable. Example The entire set of data and code of an object can made a user defined data type with the help of a class. In fact the objects are variable of the type class. Once class has been defined we can create any number of objects belonging to that class. In short, a class serves as a blueprint or a plan or a template. It specifies what data and what functions will be included in objects of that class. Defining the class doesnt create any objects, just as the mere existence of a type int doesnt create any variables. Generally, the variables declared inside the class is called as data members and the functions to access the data members are called as member functions. A class is one of the most fundamental needs for object oriented programming. For a problem to be solved in C++ the entities of the problem are to be represented as classes. Suppose we have to write a program for printing student mark sheets. The student, examiner, supervisor, mark sheet, merit list all are the entities in this case. Entities are represented as classes in a C++ program. The information that we are interested in storing about these entities is known as the attributes of the class. Attributes are of two types: data and methods (functions). One of the entities of the mark sheet program is the examiner. The data attributes of this entity (examiner) may be examiners subject, name, address, phone number, and

13

affiliation. Function attributes of the examiner entity can be reading and printing details about examiners, assigning bunch of answer sheets etc. Let us study an example of an object of student class. Consider the problem of printing student information. Following is a code to deal with the problem

// Program to demonstrate on objects : #include<iostream> #include<string> using namespace std; class student { public : int Rollno; char Name[20]; char Address[20]; void GetDetails() { cout<< Enter the roll number; cin>> Rollno; cout<< Enter the Name; cin>>Name; cout<<Enter the Address; cin>>Address; } void PrintDetails() { cout<<Roll Number is << Rollno<<\n; cout<<Name is << Name<<\n; cout<<Address is << Address<<\n; } }; void main( ) { student Student1; Student1.GetDetails();

14

Student1.PrintDetails( ); } Here, student is an example of class, which represents a real world student (an actual student). The attributes of the student class are RNo, Name, Address, GetDetails() and PrintDeatils. GetDetails() and PrintDeatils( ) are function attributes and others are data attributes. Student1 is an object of type student. Note: The data types of Name and Address; string is available as data type in C++. C++ incorporates all these extensions in another user-defined type known as class. Since this is specially introduced data-type in C++, most of the programmers use structures for holding data and classes to hold both data and functions. The only difference between structure and class in C++ is that, by default, the members of a class are private, while, by default, the members of a structure are public. Definition of a class A class is a way to bind the data and its associated functions together. It allows the data to be hidden if necessary from external use. While defining a class, we are creating a new abstract data type that can be treated as a built-in data type. A class specification has two parts: 1. Class declaration describes the type & scope of its members 2. Class function definitions describe how the class functions are implemented. class class_name { private: variable declarations; function declarations: public: variable declarations; function declarations; }; General form of class declaration

15

The keyword class specifies that what follows is an abstract data of type class_name. The body of the class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. The keywords private and public are known as visibility labels and it specify which members are private which of them are public. These should followed by a colon. Private members can be accessed only within the class whereas public members

can be accessed form outside the class. By default, the members of a class are private. If both the labels are missing, the members are private to the class. Methods : The functions we use in C++ is called as methods. There are two types of functions. One belongs to the class which is used to access the data of that particular class. This type of functions is called as member functions. The member functions may be defined inside the class or outside the class. If the function is defined outside the class, scope resolution operator is used. There are cases we can have functions which are not belong to the classes. They are called as non-member functions. Functions in C++: Syntax : Return type function name( ); Return type function name(arg); Example : void show(); main( ) { .. show(); //Function call //Function decleration //Empty function // Function with argument

16

. } void show( ) { } In C, main ( ) does not return any value. The main ( ) returns a value of type int to the operating system. int main( ); int main(int a, int b); The function that has a return value should use the return statements for termination. int main() { return 0; } Messages Passing: The process of programming in OOP involves the following basic steps: Creating classes that define objects and their behavior Creating objects from class definitions Establishing communication among objects A message for an object is request for execution of a procedure and therefore will invoke a function (procedure) 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. E.g.: employee.salary(name); Object: employee //Function body //Function definition

17

Message: salary Information: name Data Abstraction : Abstraction represents the act of representing the essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost and functions to operate on these attributes. The attributes are called data members and functions are called member functions or methods. Abstraction is useful for the implementation purpose. Actually the end user need not worry about how the particular operation is implemented. They should be facilitated only with the operations and not with the implementation. For example, Applying break is an operation. It is enough for the person who drives the car to know how pressure he has to apply on the break pad rather than how the break system functions. The car mechanic will take care of the breaking system. Encapsulation :

What is an encapsulation?(April/ May 2008)


The wrapping up of data and functions into a single unit is known as encapsulation. It is the most striking feature of the class. 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 interface between the objects data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. Inheritance : It is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the person son is a part of the class father which is again a part of the class grand father.

18

This concept provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by a deriving a new class from an existing one. The new class will have the combined features of both the classes. Grand Father Feature A Feature B

Father Feature A Feature B Feature C

Son Feature A Feature B Feature C Feature D

Abstract Classes : The classes without any objects are known as abstract classes. These classes are usually outcome of generalization process which finds out common elements of the classes of interest and stores them in a base class. The abstract classes are very important from the designers point of view. Whenever a designer has to model an abstract concept which cannot have objects, then abstract classes are handy. For example consider the class shape. It can be inherited to rectangle, ellipse, which in turn can be inherited to parallelograms into squares and circles. Except shape, all other can have objects of them. Polymorphism : It means the ability to take more than one form. An operation may exhibit different behavior in different instances. The behavior depends upon the types of data 19

used in the operation. For example the operation addition will generate sum if the operands are numbers whereas if the operands are strings then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. A single function name can be used to handle different types of tasks based on the number and types of arguments. This is known as function overloading. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as Late binding) means that the code associated with a given procedure call is not known until the time of at run-time. It is associated with polymorphism and inheritance. A function call associated with a polymorphic reference depends on the dynamic type of that reference.

*Inline functions :

What is an inline function? Explain the situations where inline expansions may not work? (May/June 2007)
An inline function is a function that is expanded in line when it is invoked. That is, the complier replaces the function call with the corresponding function code. The inline function are defined as follows: Syntax : inline function header { function body } Example : inline int cube(int a) { return (a*a*a); 20

} // Program to demonstrate inline functions : #include<iostream.h> inline float mul(float x, float y)


{

return (x*y); } inline float div(double p, double q) { return( p / q ) } int main() { float a=12.35; float b=9.32; cout<< mul(a,b); cout<<div(a,b); return 0; } The inline functions are not suitable where the function definition (body) is very lengthy and invoked very often in the program Benefits of OOP: (Describe the advantages and applications of OOPs technology. (May/June 2007)) Through inheritance, we can eliminate redundant code and extend the use of existing classes The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. It is easy to partition the work in a project based on the objects. Object oriented systems can be easily upgraded from small to large systems. Software complexity can be easily managed.

21

Object oriented systems can be easily upgraded from small to large systems. It is possible to map multiple instances of an object to co- exits without any interference. Message passing techniques for communication between objects make the interface description with external systems much simpler.

Applications of OOP: Development of Operating Systems Creation of DLL (Dynamic Linking Library) Computer Graphics Network Programming (Routers, firewalls) Voice Communication (Voice over IP) Web-servers (search engines)

Introduction to C++
A class is one of the most fundamental needs for object oriented programming. For a problem to be solved in C++ the entities of the problem are to be represented as classes. Suppose we have to write a program for printing student mark sheets. The student, examiner, supervisor, mark sheet, merit list all are the entities in this case. Entities are represented as classes in a C++ program. The information that we are interested in storing about these entities is known as the attributes of the class. Attributes are of two types: data and methods (functions). One of the entities of the mark sheet program is the examiner. The data attributes of this entity (examiner) may be examiners subject, name, address, phone number, and affiliation. Function attributes of the examiner entity can be reading and printing details about examiners, assigning bunch of answer sheets etc. Let us study an example of an object of student class. Consider the problem of printing student information. Following is a code to deal with the problem // Program to demonstrate on objects: #include<iostream> #include<string> 22

using namespace std; class student { public : int RNo; string Name; string Address; void PrintDetails() { cout<<Roll Number is << RNo<<\n; cout<<Name is << Name<<\n; cout<<Address is << Address<<\n; } }; void main( ) { student Student1; Student1.RNo = 1; Student1.Name = Vinston Raja; Student1.Address = Anna Nagar; Student1.PrintDetails( ); } Here, student is an example of class, which represents a real world student (an actual student). The attributes of the student class are Rollno, Name, Address and PrintDeatils. PrintDeatils( ) is a function attribute and others are data attributes. Student1 is an object of type student. Note: The data types of Name and Address; string is available as data type in C++.

CLASSES
*Limitations of C structures: The standard C doesnt allow the struct data type to be created like built-in types. They do not permit data hiding. Structure members can be directly accessed by the structure variables by any function anywhere in their scope. In simple words, the structure members are public members. 23

*Extensions to structures: C++ supports all the features of structures as defined in C++. It treats the userdefined data type as close to built-in data type also it provides a facility to hide the data which is one of the main percepts of OOP. In C++, a structure can have both variables and functions as members. It can also declare some of its members as private so that they cannot be accessed directly by the external functions. In C++, the keyword struct can be omitted in the declaration of structure variable. Example C++ incorporates all these extensions in another user-defined type known as class. Since this is specially introduced data-type in C++, most of the programmers use structures for holding data and classes to hold both data and functions. The only difference between structure and class in C++ is that, by default, the members of a class are private, while, by default, the members of a structure are public. Definition of a class A class is a way to bind the data and its associated functions together. It allows the data to be hidden if necessary from external use. While defining a class, we are creating a new abstract data type that can be treated as a built-in data type. A class specification has two parts: 1. Class declaration describes the type & scope of its members 2. Class function definitions describe how the class functions are implemented. class class_name { private: variable declarations; function declarations: public: variable declarations; function declarations; }; General form of class declaration

24

The keyword class specifies that what follows is an abstract data of type class_name. The body of the class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. The keywords private and public are known as visibility labels and it specify which members are private which of them are public. These should followed by a colon. Private members can be accessed only within the class whereas public members

can be accessed form outside the class. By default, the members of a class are private. If both the labels are missing, the members are private to the class.

Functions and Data Members :


The variables declared inside the class are known as data members and the functions as member functions. Only the member functions can have access to the private data and private functions. But the public members can be accessed from outside the class. Example: class item { int num; float cost; // variables declarations private by default

public: void getdata(int, float); void putdata(); }; Explanation:

// function declaration using prototype

item class name, which is used to declare instances of that class type. It contains two data members and two function members. The data members are private by default and function members are public by declaration. getdata() Assign values to the variables num and cost 25

putdata() Display the values of the variables Only the above functions can access the data members. Usually the data members are declared private, the function members are declared public. Creating Objects: Defining a class will not create any object as specifying just int will not create any variable. Once a class has been declared we can create variable of that type by using the class name. For example : item x; follows: item x,y,z; Accessing Class Members: The private data of a class can be accessed only by its member functions. Hence main() cannot access the private data of a class. The syntax for calling the member function is object-name.function-name(actual-arguments); With respect to the above example, x.getdata(27,65.5); It assigns the value 27 to num and 65.5 to cost. Similarly, x.putdata(); will display the values of num and cost. Remember a member function can be invoked only by using an object. Defining Member Functions: Member functions can be defined in two ways: 1. Outside the class definition 26 - creates a variable of x of type item. In C++, the class variables are known as objects. More than one object can be created using the statement as

2. Inside the class definition Outside the class definition: The general form of the definition is return-type class-name :: function-name(argument declaration) { function body } An important difference between a member function and a normal function is that a member function incorporates a membership identity label in the header. This label tells the compiler which class the function belongs to. The class-name :: tells the function function-name belongs to the class-name Example: void item :: getdata(int a,float b) { num = a; cost = b; } void item ::putdata() { cout << Num = << num <<\nCost = <<cost; } Characteristics: Several different classes can use the same function name. The membership label will resolve their scope. Member function can access the private data while a non member function cannot. A member function can call another member function directly, without using dot operator. Inside the class definition:

27

This method replaces the function declaration by the function definition inside the class. When the function is defined inside the class it is treated as a inline function. Normally only small functions are defined inside the class definition. class item { int num; // variables declarations private by default float cost; public: void getdata(int, float); // function declaration using prototype void putdata() { cout << Num = << num <<\nCost = <<cost; } }; Nesting of member functions: A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions. Example: #include<iostream.h> class set { int m,n; public: void input( void); void display( void); int largest(void ); }; int set :: largest(void) { if(m > = n) return (m); else return(n); } void set :: input( void ) { cout << Enter two numbers ;

28

cin >> m >>n; } void set :: display( void ) { cout<<Largest value = <<largest( ) << \n; // calling member function } int main( ) { set A; A.input( ); A.display( ); return 0; } Private member functions: Usually the member functions are normally placed in the public part, but in some situations some functions like deleting an account in the customer are more vulnerable, so it will be placed inside the private part. A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using dot operator. Example: class max { int v, p; void in( ) { cout << Enter two numbers ; cin >> v >> p; } public: void calc( ) { in( ); //simple call no object is used if ( v>=p) cout << Maximum = <<v; else cout << Maximum = << p; } }; void main( ) { max A; 29

A.in( ); A.calc( ); }

//wont work

Access Specifiers :
Access specifiers are used to access the data members and member functions of the class. There are three types of access specifiers : private: private public protected

the attributes that provide services (access) only to member functions are kept to be private.

What is the default access mode for class members?(Nov/Dec 2007)


private is the default access mode for class members. public : the attributes that provide services (access) to outsiders are to be kept as public. protected : a member declared as protected is accessible by the member functions within its class and class immediately derived from it. It cannot be accessed by functions outside these two classes (base and derived). When a protected member function is inherited in public mode, it becomes protected in the derived class too and therefore is accessible by the member functions of the derived class. It is also ready for further inheritance. A protected member, inherited in the private mode derivation, becomes private in the derived class. Although it is available to the member functions of the derived class, it is not available for further inheritance. class alpha { private: . . protected: . .

// optional // visible to member functions // within its class // visible to member functions // of its own and derived class

30

public: . . } Inheritance and Accessibility : Access Specifier public Protected Private Accessible from Own Class Yes Yes Yes Accessible from Derived Class Yes Yes No Accessible from Objects Outside Class Yes No No // visible to all functions // in the program

Default arguments :
A function can be called without specifying all its arguments. This wont work on just any function: The function declaration must provide default values for those arguments that are not specified. // Program to demonstrate default arguments #include<iostream.h> void repchar(char = *, int = 45); // declaration with default arguments int main( ) { repchar( ); repchar(=); repchar(+,30); return 0; } void repchar(char ch, int n) { for(int j=0;j<n;j++) cout<< ch; cout<<endl; }

// prints 45 asterisks // prints 45 equal signs // prints 30 plus signs

// loops n times // prints ch

In this program the function repchar( ) takes two arguments. It is called three times from main( ). The first time it is called with no arguments, the second time with one, and the third time with two. Why do the first two calls work? Because the called

31

function provides default arguments, which will be used if the calling program doesnt supply them. How to represent the default arguments? The default arguments follow an equal sign, which is placed directly after the type name. The default arguments are specified in the declaration for repchar( ) : void repchar(char = *, int = 45); // declaration

You can also use variable names, as in void repchar(char reptChar = *, int numberReps = 45); If one argument is missing when the function is called, it is assumed to be the last argument. The repchar( ) function assigns the value of the single argument to the ch parameter and uses the default value 45 for the n parameter. If both arguments are missing, the function assigns the default value * to ch and the default value 45 to n. Thus the three calls to the function all work, even though each has a different number of arguments. A default argument is checked for type at the time of declaration and evaluated at the time of call. One important point to note is that only trailing arguments can have default values and therefore we must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of an argument list Default arguments are useful in situations where some arguments always have the same value. For instance, pass mark to a subject remain the same for all students. It also provides a greater flexibility to the programmers. A function can be written with more parameters than are required for its most common application. Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation. Advantages of providing the default arguments are :

32

1. We can use default arguments to add new parameters to the existing functions. 2. Default arguments can be used to combine similar functions into one.

Function Overloading :
A single function name can be used to handle different types of tasks based on the number and types of arguments. This is known as function overloading. Using the concept of function overloading; we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type. For example, an overloaded add( ) function handles different types of data as shown below: // Declarations int add(int a, int b); int add(int a, int b, int c); double add(double x, double y); double add(int p, double q); double add(double p, double q); // Function calls cout << add(5,10); cout << add(15,10.0); cout << add(12.5,7.5); cout << add(5,10,15); cout << add(0.75,5);

// prototype 1 // prototype 2 // prototype 3 // prototype 4 // prototype 5 // uses prototype 1 // uses prototype 4 // uses prototype 3 // uses prototype 2 // uses prototype 5

A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. // Program to demonstrate function overloading #include<iostream> //Declarations (prototypes) int volume(int); 33

double volume(double, int); long volume(long, int, int); int main( ) { cout << volume(10) << \n; cout << volume(2.5, 8) << \n; cout << volume(100L, 75, 15) << \n; return 0; } // Function definitions int volume (int s) { return(s * s * s); } double volume (double r, int h) { return(3.14 * r * r * h); } double volume (long l, int b, int h) { return(l * b * h); } The output of the above program would be : 1000 157.26 112500 // cube

// cylinder

// rectangular box

Friend Functions :
In OOP environment, 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. To allow a function (non-member) to have access to the private data of a class, the function has to be made friendly to that class. To make an outside function friendly to a class, we have to simply declare this function as a friend of the class as shown below :

34

class ABC { . . public : . . friend void xyz(void); }; The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope resolution operator : :. The functions that are declared with the keyword friend are known as friend functions. A friend function can be declared as a friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class. Characteristics (certain special characteristics) of Friend functions: It is not in the scope of the class to which it has been declared as friend. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object. Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member access.(e.g. A . x). It can be declared either in the public or private part of a class without affecting its meaning. Usually, it has the objects as arguments. // data members // member functions // declaration

// program to demonstrates the use of a friend function #include<iostream> using namespace std; 35

class sample { int a; int b; public: void setvalue( ) { a = 25; b = 40; } friend float mean (sample s);

// declaration

}; float mean (sample s) { return float(s.a + s.b) / 2.0 ; } int main( ) { sample X; // object X X.setvalue( ); cout << Mean Value = << mean(X) << \n; return 0; } The output of the above program would be : Mean Value = 32.5 The friend function accesses the class variables a and b by using the dot operator and the object passed to it. The function calls mean(X) passes the object X by value to the friend function. Member functions of one class can be friend functions of another class. In such cases, they are defined using the scope resolution operator as shown below: class X { . . int fun1( ); . }; class Y { . . 36 // member function of X

friend int X : : fun1( ); . }; The function fun1 ( ) is a member of class X and a friend of class Y. We can also declare all the member functions of one class as the friend functions of another class. In such cases, the class is called a friend class. This can be specified as follows: class Z { . friend class X; }; //program with a function friendly to two classes #include<iostream> using namespace std; class ABC ; class XYZ { int x; public : void setvalue(int i) { x = i ;} friend void max(XYZ, ABC); }; class ABC { int a; public : void setvalue(int i) { a = i ;} friend void max(XYZ, ABC); }; // definition of friend function void max(XYZ m, ABC n) { if(m.x >= n.a) cout << m.x; else cout << n.a; 37 // all member functions of X are friends to Z

// forward declaration

} int main( ) { ABC abc; abc.setvalue(10); XYZ xyz; xyz.setvalue(20); max(xyz, abc); return 0; } The output of the above program would be : 20 Note : The function max( ) has arguments from both XYZ and ABC. When the functions max( ) is declared as a friend in XYZ for the first time, the compiler will not acknowledge the presence of ABC unless its name is declared in the beginning as class ABC; This is known as forward declaration. Returning Objects : A function cannot only receive objects as arguments but also can return them. The following program illustrates how an object can be created(within a function) and returned to another function. // program to demonstrate returning objects #include<iostream> using namespace std; class complex { float x; // real part float y; // imaginary part public: void input(float real, float imag) { x = real; y = imag; } friend complex sum(complex, complex); // friend function declaration void show(complex);

38

} complex sum(complex c1, complex c2) { complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return(c3); } void complex : : show(complex c) { cout << c.x << + j << c.y << \n ; } int main() { complex A, B, C; A.input(3.1, 5.65); B.input(2.75, 1.2); C = sum(A,B); cout << A = ; A.show(A); cout << B = ; B.show(B); cout << C = ; C.show(C); return 0; } // friend function definition // object c3 is created // returns object c3

// C = A + B

Upon execution, above program would generate the following output : A = 3.1 + j5.65 B = 2.75 + j1.2 C = 5.85 + j6.85 The program adds two complex numbers A and B to produce a third complex number C and displays all the three numbers.

Const and Volatile functions :


If a member function does not alter any data in the class, then we may declare it as a const member function. The compiler will generate an error message if such functions try to alter the data value. The qualifier const is appended to the function prototypes (in both declaration and definition). The syntax of declaring a const function is given below : 39

<return type> <function name>(argument1,argument2,) const ; Example: void mul(int, int) const ; double get balance( ) const ; The syntax of defining a const function is given below : <return type> <function name>(argument1,argument2,) const { <The function body> } Example : void PrintDetails( ) const { cout << Roll Number is : << RollNumber << \n; cout << Name is : << Name << \n; cout << Address is : << Address << \n; }

Constant Objects :
Const objects are objects that are not modifiable. C++ provides safeguarding against accidental modification by not allowing access of the object to a normal member function. Const object, obviously, is not allowed to do operations which modify the object. Only functions that are defined as const can be accessed by const objects. Even public variables of the object are not modifiable. Const member functions are functions that make sure that an object is not modified. A normal function cannot be invoked by const objects. Thus the object maintains its integrity. When we do not want any accidental change in the objects properties, we should define the object as a const object. //ConstObj.cpp #include<iostream> #include<string> using namespace std;

40

class student { public: int RollNumber; string Name; string Address; void PrintDetails( ) const {

/* this function is now constant, it can now be accessed by const bject of class student*/

cout<<RollNumber is<<RollNumber<<\n; cout<<Name is<<Name<<\n; cout<<Address is<<Address<<\n; } }; void main() { student Student1; Student1.RollNumber=1; Student1.Address=NewDelhi; Student1.Name=Rahul; Student1.PrintDetails(); Student Student2= Student1; Student Student3; Student3= Student1; Student2.PrientDetails(); Student3.PrientDetails(); const student OtherStudent= Student1; //Following is erroneous if PrintDetails( )is not const OtherStudent.PrintDetails(); /* Following line wontt compile because it tries to modify a constant object*/ OtherStudent.RollNumber=5; /*Following will work*/ cout<<OtherStudent.RollNumebr; }

Volatile functions:
A member function can be declared as volatile if it is invoked by a volatile object. A volatile objects value can be changed by external parameters which are not under the control of the program.

41

For example, an object taking an input from a Network Interface Card does not take input from our program. As and when the hardware interrupts, the values related to it change without our programs knowledge. A sample definition of volatile function and volatile object is shown below: class NICClass { public: void CheckValueForNIC volatile { // function body } . }; volatile NICClass NICObject;

// a volatile function definitions

// a volatile object definition

Local Classes:
When a class is defined inside functions it is called as local class. Let us consider an example to understand local classes. // Program to demonstrate Local classes : #include<iostream> #include<string> using namespace std; void main( ) { int RollNo = 3 ; void TestStudent(int); TestStudent (RollNo); } void TestStudent(int Roll) { int TestValue = 100 ; static int StaticTestValue = 200 ; class student // Now this class is a local class! { // only in TestStudent function the class is available public : int RollNumber; string Name;

//prototype of TestStudent function ; class student is //not known here

42

string Address; void PrintDetails( ) { cout << TestValue // this is not valid since TestValue and cout<<::StaticTestValue;//StaticTestValue are private variable //of the class cout << Roll Number is : <<RollNumber<<\n; cout << Name is : <<Name<<\n; cout << Address is : <<Address<<\n; } }; // now this function cannot be defined // outside this class

student Student1; Student1.RollNumber = Roll; Student1.Name = Ragul; Student1.Address = New Delhi; Student1.PrintDetails( ); } Following are some restrictions on the use of local classes: They cannot use auto local variables of the container function. (Eg. TestValue) They can access static local variables or extern variables(globally defined) of the container function(Eg.StaticTestValue ) They cannot contain static member themselves They cannot define their function outside the class boundaries.Here the PrintDetails( ) must be defined inside the class. Their private variables are not available to container function unless declared as friend.

43

44

También podría gustarte