Вы находитесь на странице: 1из 35

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

SUBJECT NAME : EC2202 / DS & OOP IN C++ SEMESTER : III BRANCH / SEC : ECE ____________________________________________________________________________________________

UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects, constructors and destructors ,operators overloading and type conversions . PART B (16 MARK) 1. State the merits of object oriented methodology. Merits: Can create new programs faster because we can reuse code Easier to create new data types Easier memory management Programs should be less bug-prone, as it uses a stricter syntax and type checking. Data hiding', the usage of data by one program part while other program parts cannot access the data 2. Describe the application of OOP technology Applications of OOP: 1. Real time systems 2. Simulation and modeling 3. AI and expert systems 4. Neural networks and parallel programming. 5. Decision support and office automation systems 6. Object Oriented Databases 7. Hypertext and hypermedia 8. CIM /CAM/CAD systems 2. Explain the basic concepts of object oriented programming in detail with example. BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING: 1. Objects 2. Classes 3. Data abstraction and encapsulation 4. Inheritance 5. Polymorphism 6. Dynamic binding 7. Message passing Objects:
1

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

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. 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. shows two notations that are used in object-oriented analysis and design. Two ways of representing an object

Classes: 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. For example, mango, apple and orange are members of the class fruit. fruit mango; will create an object mango belonging to the class fruit Data Abstraction and Encapsulation: 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. 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
2

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

attributes. The attributes are called data members and functions are called member functions or methods. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).

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 bird robin is a part of the class flying bird which is again a part of the class bird.

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.

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

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 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. It allows objects to have different internal structures to share the same external interface. A single function Draw() is used to handle different type and different number of arguments.

Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic Binding (late binding) means the code associated with the given procedure call is not known until the time of the call at run-time. It is associated with the polymorphism and inheritance. Message Passing: The process of programming in OOP involves the following basic steps: 1. Creating classes that define objects and their behavior 2. Creating objects from class definitions 3. Establishing communication among objects A message for an object is request for execution of a procedure and therefore will invoke a

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

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.

4. Explain the Basic data types in C++ Data types in C++ can be classified under various categories: Hierarchy of C++ data types

Size and range of C++ basic data types


5

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

Enumerated data type Provides a way to attach names to numbers, thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2, and so on. Examples:

By using tag names, we can declare new variables. Examples,

Derived data types


6

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

1. Arrays Collection of data elements with same data type. Eg. Char string[4] = xyz; 2. Functions - Used to reduce the size of a program by calling and using them at different places in the program. Eg . Void show(); /* function declaration */ main() { ----show(); /*function call */ ------} void show() /* function definition */ { -------} 3. Pointers

5. Explain Operators in C++


7

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

All operators in C are also used in C++. In addition to insertion operator << and extraction operator >> are used in C++. The other new operators in C++ are, :: ::* ->* .* delete endl new setw Scope resolution operator Pointer-to-member declarator Pointer-to-member operator Pointer-to-member operator Memory release operator Line feed operator Memory allocation operator Field width operator

scope resolution operator Scope resolution operator is used to uncover the hidden variables. It also allows access to global version of variables. Eg: #include<iostream.h> int m=10; // global variable m void main ( ) { int m=20; // local variable m cout<<m=<<m<<\n; cout<<: : m=<<: : m<<\n; } output: 20 10 (: : m access global m) Scope resolution operator is used to define the function outside the class. Syntax: Return type <class name> : : <function name>

Member-dereferencing operator C++ permits to access the class members through pointers. It provides three pointer-to-member operators for this purpose, Eg : : * To declare a pointer to a member of a class * To access a member using object name and a pointer to that member * To access a member using a pointer to the object and a pointer to that member

Memory Management Operators


8

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

Need for Memory Management operators The concept of arrays has a block of memory reserved. The disadvantage with the concept of arrays is that the programmer must know, while programming, the size of memory to be allocated in addition to the array size remaining constant. In programming there may be scenarios where programmers may not know the memory needed until run time. In this case, the programmer can opt to reserve as much memory as possible, assigning the maximum memory space needed to tackle this situation. This would result in wastage of unused memory spaces. Memory management operators are used to handle this situation in C++ programming language There are two types of memory management operators in C++:

new delete

These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways. new operator: The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any type. General syntax of new operator in C++: The general syntax of new operator in C++ is as follows: pointer variable = new datatype; In the above statement, new is a keyword and the pointer variable is a variable of type datatype. For example: int *a=new int; In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated. Dynamic variables are never initialized by the compiler. Therefore, the programmer should make it a practice to first assign them a value. The assignment can be made in either of the two ways: int *a = new int; *a = 20; or int *a = new int(20); delete operator:
9

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

The delete operator in C++ is used for releasing memory space when the object is no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory. General syntax of delete operator in C++: delete pointer_variable; In the above example, delete is a keyword and the pointer variable is the pointer that points to the objects already created in the new operator

Advantages of new operator over the function malloc() 1. It automatically computes the size of the data object. No need for sizeof operator 2. It automatically returns the correct pointer type, no need for type cast operator 3. It is possible to initialize the object while creating the memory space. 4. new and delete can be overloaded. Example: #include void main() { //Allocates using new operator memory space in memory for storing a integer datatype int *a= new a; *a=100; cout << " The Output is:a="<<*a; //Memory Released using delete operator delete a; } output: The Output is:a=100 Manipulators Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw. Eg. cout << setw(5) << sum << endl; The manipulator setw(5) specifies a field width 5 for printing the values of the variable sum.

6. (i) Explain about expressions and their types. (ii) Describe about implicit conversions.
10

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

(i) An expression is a combination of operators, constants and variables arranged as per the rules of the language. Seven types of expressions

11

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

(ii) Implicit Conversions In an expression, wherever data types are mixed C++ performs the conversions automatically. This process is known as implicit or automatic conversion. The rule is the smaller type is converted to the wider type. The water-fall model shown in fig. illustrates this rule. Waterfall model of type conversion:
12

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

The char or short int appears in an expression, it is converted to an int. This is called integral widening conversion. 7. Explain Control Structures. All program processing can be coded by using by three logic structures. Three control structures: 1. Sequence structure (straight line) 2. Selection structure (branching) eg. if statement,switch statement 3. Loop structure (iteration or repetition) do-while, while, for statments Basic control structures

13

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

14

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

15

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

8. What is an inline function? INLINE FUNCTIONS: 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: inline function header { function body } Example : inline int cube(int a) { return (a*a*a); } Program : #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()
16

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

{ float a=12.35; float b=9.32; cout<< mul(a,b); cout<<div(a/b); return 0; } 9. Explain Function Overloading with example. Function overloading means we can use the same function name to create functions that perform a variety of different tasks. Eg: An overloaded add ( ) function handles different data types as shown below. // Declarations i. int add( int a, int b); //add function with 2 arguments of same type ii. int add( int a, int b, int c); //add function with 3 arguments of same type iii. double add( int p, double q); //add function with 2 arguments of different type //Function calls add (3 , 4); //uses prototype ( i. ) add (3, 4, 5); //uses prototype ( ii. ) add (3 , 10.0); //uses prototype ( iii. ) The function selection involves the following steps: 1. Exact Match The complier first tries to find an exact match in which the types of actual arguments are the same, and use that function. 2. Integral Promotions If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as, char to int float to double to find the match 3. Build-in conversions The compiler uses build-in conversions to actual arguments. 4. If all of the steps fail, then the compiler will try the combinations of above three steps to find the unique match. Example: #include<iostream.h> int volume(int); double volume(double,int); long volume(long,int,int);
17

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

int main() { cout<<volume(10)<<"\n"; cout<<volume(2.5,8)<<"\n"; cout<<volume(100,75,15)<<"\n"; return 0; } int volume(int s) { return(s*s*s); } double volume(double r,int h) { return(3.14*r*r*h); } long volume(long l,int b,int h) { return(l*b*h); } Output: 1000 157.26 112500

10. Explain Classes and Objects in C++. The general form of a class declaration in C++ is: class class_name { private: variable function public: variable function };

declarations; declarations; declarations; declarations;

-The keyword class indicates that an abstract data type called class_name will be specified. -The class body is enclosed within braces and terminated by a semicolon. -The variables declared inside the class are known as data members and the functions are known as member functions. -These functions and variables are usually grouped under two sections: namely, private and
18

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

public. -Only the member functions can have access to the private data members and private functions. However, the public members can be accessed from outside the class. -Note that declaring data variables as public defeat the idea of data hiding and therefore should be avoided. Simple Class Example class item { private: int number; float cost; public: void getdata(int a, float b); void putdata(); }; Here, we have defined a class called item. This name is used to declare objects of that class. The data members (number and cost) are declared as private, while the member functions (getdata() and putdata()) are declared as public. As mentioned earlier, these two functions provide the only access to the two data members from outside the class. Note that, at this stage class definition does not allocate any memory space. Objects Once a class has been defined, we can create objects of that type as follows: item x; This statement creates an object x of type item. At this stage, memory space is allocated to the object x. We may also declare more than one object in one statement, for example item x, y, z; Another way to create objects is by placing their names immediately after the closing brace in the class definition, for example: class item { } x, y, z; Accessing Class Members The public member functions can be accessed only from outside the class. This can be done using the dot operator, for example x.getdata(100, 75.5); This function call statement is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing the getdata() function.
19

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

Similarly, the statement x.putdata(); would display the values of number and cost. While the statement x.number =100; is illegal because number is a private member and cannot be accessed from outside the class. When a variable is declared as public, it can be accessed by the objects directly, for example: class xyz { private: int x; int y; public: int z; }; xyz p; // create object p p.x = 0; // error, x is private p.z = 10; // OK, z is public However, the public declaration of data conflicts with the OOP concept data hiding and therefore should be avoided. Definition of Member Functions Class member functions can be defined in two places: Outside the Class Definition Example: void item :: getdata(int a, float b) { number = a; cost = b; } Here, the membership label item :: tells the compiler that the function getdata() belongs to the class item. That is, the scope of the function getdata() is restricted to the class item specified in the header line. The symbol :: is called the scope resolution operator. Note the statements number = a; cost = b; show that the member functions can have direct access to private data items. Similarly, the function putdata() is defined outside the class item as follows: void item :: putdata() { cout << Number : << number; cout << Cost : << cost;
20

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

} Inside the Class Definition Example: class item { private: int number; float cost; public: void getdata(int a, float b); void putdata() { cout << Number : << number << ; cout << Cost : << cost << ; } }; Note: Normally, only small functions are defined inside the class definition. A Complete C++ Program with Class The following program includes all the details discussed so far: #include <iostream> using namespace std; class item { private: int number; float cost; public: void getdata(int a, float b); void putdata() { cout << number : << number << ; cout << cost : << cost << ; } }; void item :: getdata(int a, float b) { number = a; cost = b; } void main() { item x; // create object x
21

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

cout << Object x ; x.getdata(100, 299.95); x.putdata(); item y; // create another object y cout << Object y ; x.getdata(200, 175. 50); x.putdata(); } The output of the above program is: Object x number :100 cost :299.95 Object y number :200 cost :175.5 Nesting of Member Functions We have shown that a class member function can be called only by an object of that class using a dot operator. However, a member function can be called inside another member function of the same class. This is called nesting of member functions. Example: #include <iostream> using namespace std; class set { private: int m, n; public: void input(); void display(); int largest(); }; int set :: largest() { if(m >= n) return m; else return n; } void set :: input() { cout << Input values of m and n << ; cin >> m >> n; }
22

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

void set :: display() { cout << Largest value = << largest() << ; //calling member function } main() { set A; A.input(); A.display(); } The output of the above program would be: Input values of m and n 25 18 Largest value = 25 Private Member Functions Some tasks such as deleting a customer account, or providing an increment to an employee may require certain functions to be hidden (like private data) from the outside calls. We can place these functions in the private section. Note that a private member function can only be called by another member function of its class, and cannot be called by an object. Example: class sample { private: int m; void read(); // private member function public: void update(); void write(); }; sample s1; s1.read(); // wont work; objects cannot access // private members from outside the class The function call statement s1.read(); is illegal. Instead, the function read() can be called by the function update() to update the value of m. void sample :: update()
23

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

{ read(); // simple call; no object used } 11. Explain about constructors and its types in detail. A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class Eg: class integer { public: integer( );//constructor } Default constructor The constructor with no arguments is called default constructor Eg: Class integer { int m,n; Public: Integer( ); . }; integer::integer( )//default constructor { m=0;n=0; } the statement integer a; invokes the default constructor Parameterized constructor constructor with arguments is called parameterized constructor Eg; Class integer { int m,n; public: integer(int x,int y) { m=x;n=y;
24

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

} To invoke parameterized constructor we must pass the initial values as arguments to the constructor function when an object is declared. This is done in two ways 1.By calling the constructor explicitly eg: integer int1=integer(10,10); 2.By calling the constructor implicitly eg: Integer int1(10,10); Default argument constructor The constructor with default arguments are called default argument constructor Eg: Complex(float real,float imag=0); The default value of the argument imag is 0. The statement complex a(6.0) assign real=6.0 and imag=0 the statement complex a(2.3,9.0) assign real=2.3 and imag=9.0 The ambiguity between default constructor and default argument constructor The default argument constructor can be called with either one argument or no arguments. when called with no arguments ,it becomes a default constructor. When both these forms are used in a class ,it cause ambiguity for a statement such as A a; The ambiguity is whether to call A::A() or A::A(int i=0) Copy constructor A copy constructor is used to declare and initialize an object from another object. It takes a reference to an object of the same class as an argument. Eg: integer i2(i1); would define the object i2 at the same time initialize it to the values of i1. Another form of this statement is Eg: integer i2=i1; The process of initializing through a copy constructor is known as copy initialization. Dynamic constructor Allocation of memory to objects at time of their construction is known as dynamic constructor. The memory is allocated with the help of the new operator Eg: Class string { char *name; int length; public: string( )
25

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

{ length=0; name=new char[length +1]; } void main( ) { string name1(Louis),name3(Lagrange); //dynamic constructor } Multiple constructors (constructor overloading) The class that has different types of constructor is called multiple constructors Eg: class integer { public: integer( ) //default constructor { m=0;n=0; } integer(int a,int b) //parameterized constructor { m=a; n=b; } integer(&i) //copy constructor { m=i.m; n=i.n; } }; void main() { integer i1; //invokes default constructor integer i2(45,67);//invokes parameterized constructor integer i3(i2); //invokes copy constructor } Special characteristics of constructor They should be declared in the public section They are invoked automatically when the objects are created They do not have return types, not even void and therefore, and they cannot return values They cannot be inherited, though a derived class can call the base class They can have default arguments Constructors cannot be virtual function

26

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

12. Explain copy constructor with suitable C++ coding. Constructor: A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class its created. A constructor is declared and defined as follows: class sample { int m,n; public: sample() { m = n = 0; } // some code }; int main() { sample s; // object is created // some code } During the object creation, it also initializes the data members m and n to 0. Default Constructor: A constructor that accepts no parameters is called the default constructor. Characteristics of a constructor: They should be declared in the public section They are invoked automatically when the objects are created They do not have return types, not even void and therefore, and they cannot return values They cannot be inherited, though a derived class can call the base class They can have default arguments Constructors cannot be virtual function Copy constructor: A copy constructor takes a reference to an object of the same class as itself as an argument. Example: #include<iostream.h> #include<conio.h>
27

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

class code { int id; public: code(){} code(int a) {

// default constructor // parameterized constructor

id=a; } code(code&x) // copy constructor { id=x.id; } void display(void) { cout<<id; } }; int main() { clrscr(); code a(100); code b(a); // copy constructor called, object b copies the values of object a code c=a; // copy constructor called, object c copies the values of object a code d; d=a; cout<<"\nid of a:"; a.display(); cout<<"\nid of b:"; b.display(); cout<<"\nid of c:"; c.display(); cout<<"\nid of d:"; d.display(); getch(); return 0; } Output: id of a:100 id of a:100 id of a:100 id of a:100 13. State the rules to be followed while overloading an operator. Write a program to illustrate overloading. Operator overloading The mechanism of giving such special meanings to an operator is known as Operator
28

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

overloading. It provides a flexible option for the creation of new definitions for C++ operators. List out the operators that cannot be overloaded. Class member access operator (. , .*) Scope resolution operator (::) Size operator ( sizeof ) Conditional operator (?:)

Purpose of using operator function To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done by Operator function, which describes the task. Operator functions are either member functions or friend functions. The general form is return type classname :: operator (op-arglist ) { function body } where return type is the type of value returned by specified operation. Op-operator being overloaded. The op is preceded by a keyword operator. operator op is the function name. Overloading Unary Operators When unary operators are overloaded using member functions it takes no explicit arguments and return no explicit values. When binary operators are overloaded using member functions, it takes one explicit argument. Also the left hand side operand must be an object of the relevant class. #include<iostream.h> class unary { private: int x,y,z; public: unary(void) { cout<< "Enter Any Three Integer Nos. : "; cin>>x>>y>>z; } void display(void) { cout<< endl<< " The Three Nos. Are : "<< x<< " , "<< y<< " , "<< z; } void operator --() { x = --x; y = --y;
29

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

z = --z; } void operator ++() { x = ++x; y = ++y; z = ++z; } }; void main() { clrscr(); unary s; s.display(); --s; s.display(); ++s; s.display(); getch(); } Output: Enter Any Three Integer Nos. : 1 2 3 The Three Nos. Are : 1,2,3 The Three Nos. Are : 0,1,2 The Three Nos. Are :1,2,3 Overloading Binary Operators The same mechanism can be used to overload a binary operator. Example: #include <iostream.h> #include<conio.h> class complex { float x; float y; public: complex(){} complex(float real,float image) { x=real;

// overload function called // overload function called

//real part //imaginary part //constructor 1 //constructor 2

30

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

y=image; } complex operator + (complex); void display(void); }; complex complex::operator+(complex c) { complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex::display(void) { cout<<x<<"+j"<<y; } int main() { clrscr(); complex c1,c2,c3; c1=complex(2.5,3.5); c2=complex(1.6,2.7); c3=c1+c2; cout<<"c1 ="; c1.display(); cout<<"c2 ="; c2.display(); cout<<"c3 ="; c3.display(); getch(); return 0; } Output of the program:

//operator overloading function

//invokes constructor1 //invokes constructor 2

31

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

Implementation of overloaded + operator

Overloading Binary operators using friends

32

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

Rules for overloading operators

14. Explain Type Conversions in detail. A casting operator is a function that satisfies the following conditions It must be a class member. It must not specify a return type. It must not have any arguments.

33

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

The general form of overloaded casting operator is operator type name ( ) { .. // function statements } It is also known as conversion function. basic data type to class type Conversion from basic data type to class type can be done in destination class. Using constructors does it. Constructor takes a single argument whose type is to be converted. Eg: Converting int type to class type class time { int hrs,mins; public: . time ( int t) //constructor { hours= t/60 ; //t in minutes mins =t % 60; } }; Constructor will be called automatically while creating objects so that this conversion is done automatically. class to basic type conversion class to basic type conversion with an example. Using Type Casting operator, conversion from class to basic type conversion can be done. It is done in the source class itself. Eg: vector : : operator double( ) { double sum=0; for(int i=0;i<size;i++) sum=sum+v[ i ] *u[ i ] ; return sqrt ( sum ) ; } This function converts a vector to the corresponding scalar magnitude. One class to another class conversion one class to another class conversion with an example. Conversion from one class type to another is the combination of class to basic and basic to class type conversion. Here constructor is used in destination class and casting operator function is used in source class. Eg: objX = objY objX is the object of class X and objY is an object of class Y. The class Y type data is converted into class X type data and the converted value is assigned to the obj X. Here class Y is the source class and class X is the destination class.
34

EC2202 / DATA STRUCTURE AND OBJECT ORIENTED PROGRAMMING IN C++ _____________________________________________________________________________________

UNIVERSITY QUESTIONS UNIT 1 2009 apr/may Part A when do we declare a member of a class static why is it necessary to overload an operator Part B a. what is a friend function? what are the merits and demerits of using friend function? Define a class string. Use overload = = operator to compare two strings. b. what is a parameterized constructor?Explain with example. what is a conversion function? how is it created? explain its syntax. 2010 apr/may 1. How is a class declared in C++? 2. What is a scope resolution operator and how can it be used for global variable? 11. (a) (i) Give the syntax and usage of the reserved word inline with two examples. (8) (ii) Explain the importance of constructors and destructors with example. (8) Or (b) What is operator overloading? Overload the numerical operators +and / for complex numbers addition and division respectively. (16) 2010 nov/dec 1. What effects do the visibility labels private, protected and public have on the members of a class? 2. What are the advantages of operator overloading? 11. (a) (i) Compare and contrast Structured Programming and Object Oriented Programming. (8) (ii) Distinguish between Data Encapsulation and Data Abstraction. (4) (iii) Mention the purpose of Constructor and Destructor functions. (4) Or (b) (i) Explain the control structures of C++ with suitable examples. (12) (ii) Define function overloading with a simple example. (4) 2011 1. Define polymorphism 2. What is the use of construction? 11. (a) Explain in detail about classes and objects with example. (16) Or (b) With general syntax and example describe the operating overloading for unary and binary operators in detail. (16)
35

Вам также может понравиться