Sei sulla pagina 1di 87

OBJECT ORIENTED PROGRAMMING

Chapter 1: Introduction to oop


In the beginning when computers came into existence, the programs were coded in the form of binary 0s and 1s and they were loaded with the help of mechanical switches. After the high level languages were introduced the codes were written in general English like language, which are easy to understand. During this period of programming languages are simple and are concerned to relatively simple tasks like calculations, programs were pretty short i.e limited to few hundred lines of source code. As the capacity and capability of computer increased, so the needs of writing more complex programs also increased. But earlier programming languages are unable to perform the tasks according to the needs because the programs are more complex now. These programs suffered from following limitations: (a). No facility of reuse an existing code, so same piece of code has to be duplicated. (b). All variables are used globally, so every time the data is changed. . Writing, understanding and maintaining long programs became programmers nightmare.

STRUCTURED PROGRAMMING
In late 60s and early 70s the solutions of limitations mentioned above the structured programming came into existence. A structured program is built by breaking the complex or big program in small pieces and each piece have its own data and logic and each piece perform its given task. A structured program minimizes the chance of errors, and helps to isolate problems, if any. Structured program help you to write cleaner code and maintain control over each function. All this makes the development and maintenance of code fast as well as efficient.

ABSTRACTION
Abstraction permits the programmer to look at something without being concerned with its internal details. In structured programming it is enough to know which task is performed without knowing how that task is performed as long as the function is going well. Structured programming ruled for almost two decades. With the constant improvement of hardware and more demands of texture rich more programs from the users, the complexity of programs increased, and thats the time when structured programming started showing its weakness.

REASONS OF FAILURE OF STRUCTURED PROGRAMMING:


(a). In structured programs, data types are processed in many functions, and when change occurs in data, modification must be made at every location that acts on those data within the program. This is frustrating and time-consuming task for large-sized programs: (b). Structured programming emphasizes on fitting a problem to the procedural approach of a language rather than a solution.

OBJECT ORIENTED PROGRAMMING

(OOP)

The object oriented programming is built on foundation laid by the structured programming concepts and the data abstraction. The fundamental change in OOP is that a program is designed around the data being operated rather than the operation upon themselves. The basic behind OOP is to combine data and the function that operate on the data in a single unit. This unit is called as OBJECT.

CHARACTERISTICS OF OBJECT-ORIENTED LANGUAGES


OBJECT: In OOP the problem is divided into objects, so thinking in term of
object rather than functions makes the designing easier. Few candidates are mentioned are mentioned below which can be treated as an object in different languages: Employee in a payroll system Computers in network system Students in a class etc.

CLASSES:
Classes are user-defined data type and behave like built in data types of a programming language. The entire set of data and code of an object can be made user defined data type with help of a class. Once a classs has been defined, we can create any number ob objects belonging to that class. Each object is associated with the data of class by which they are created. A class is thus a collection of objects of similar type. For example mango, apple and orange are members of class fruit(class name). Fruit mango; This statement will create an object mango belonging to class fruit.

DATA ENCAPSULATION
The wrapping of data and functions into single unit (class) is known as encapsulation. Data encapsulation is most powerful feature of a class. The data is only accessible to the functions which are defined in the class ant not to the functions defined outside the class.

INHERITENCE
Inheritance is the process by which the features of class can be used by other classes. In the concepts of inheritance we can add additional features to an existing class without modifying it. This is possible by deriving new class from the existing one and the new class will have the new features as well as old features. The new class is called as derived class and the old and existing class is called as base class. The advantage of inheritance mechanism is that programmer can reuse an existing code as per his needs without rewriting the entire code. Base class A Feature A

Feature A Feature X i.e derived class y

Feature A Feature Y i.e derived class x

In above example X and Y classes are derived from A class. X and Y class has their own features of the base class A.

POLYMORPHISM
Polymorphism is a technique that is used in performing multiple task with a single function. Shane Draw ( ) Circle object Draw (circle) Box object Draw (box) Triangle object Draw (triangle)

In above example there is a function called draw and we can use it in drawing different shapes. The end result is that single function name can used for the same operation performed on related derived classes even if the achievement of function differs from class to class.

REUSABILITY
In object-oriented programming technique, once a program is completed and tested, it can be used in other programs. This is called as reusability. The programmer can add new feature to the old or existing program. The programmer can devote the time to writing the new code.

Chapter 2 Beginning with c++

What is c++ ?
C++ is an object oriented language. Like c, c++ was also developed AT&T Bell Laboratries in Murray Hill, Newjersey, USA, by Bjarne Stroustrup in early 1980s. Stroustrup based c++ on c because of cs brevity, its sutability to system programming, and its popularity. C++s OOP aspect was inspired by a computer stimulation language called Simula67. Class was a major addition in the original c language, Stroustrup called the new language c with classes. In 1983 the name was changed to c++, this means an increment version of c. therefore all c programs are also c++ programs.

A SIMPLE C++ PROGRAM


This is a program to print message on the screen #include<iostream.h> //include header file main ( ) { Cout<< enter value of a:; //print the message on the screen. Int a;

// variable declaration. Cin>>a ; // passing value to the variable. Return (0); //end of program

PROGRAM FEATURES #include<iostream.h>

It is a preprocessor directive, it contains declarations for the identifier cout and the operator<<. The header file iostream.h should be included at the beginning of all programs that use input/output statements.

Main ( )
Every c++ program must have a main ( ). Main ( ) is the staring point of a c++ program, so without main ( ) a c++ program never executes.

Exercise:
1. Write a program to display the following using cout statement: Maths = 90

Physics Chemistry

= 77 = 69

2. Write a program to accept two numbers and display the greater on screen. 3. Write a program to print your name up to n, input n. 4. Write a program to read values of a, b and c and display the value of x, where (x=a/b-c). Test your program for the following values: A. a=250, b=85, c=25 B. a=300, b=70, c=70.

Chapter 3 Expression and Control Structures


As mentioned earlier c++ is a superset of c and therefore most expressions and control statements of c are valid in c++ with their formats unchanged (e.g. if statement, for statement, while and do while, switch case).

USER DEFINED DATA TYPES


In addition to basic data types c++ allows you to define your own special data types such as structures, enumeration. In this chapter we will discuss enumeration.

ENUMERATION
An enumeration is user defined data type which provides a way to attach names to numbers. The syntax of enum statement is similar to the statement of structures.

SYNTAX:
Enum type name {constant name 1=value 1, } Enum is keyword, typename stands for the name, constant_name is the name of a constant that can cout<<today is holiday<<end1<< enjoy.; If (a>sun &&a<=sat) Cout << today is the working day<<end<< work hard ; else

Cout<< invalid day.. Getch ( );

DYNAMIC INITIALIZATION OF VARIABLES


Unlike c, in c++ declaration and initialization of variables can be done simultaneously at the place where the variable is used for first time.

EXAMPLE:
#include<iostream.h> Void main ( ) { Cout << enter first number: ; Int a; Cin>>a; //declaration of variable

Cout<< enter second number: ; Int b; Cin>>b; Int c= a+b; Cout << Result is:<<c; } //dynamic declaration //declaration of variable

REFERENCE VARIABLE
A reference variable provides an alias for previously declared variable.

EXAMPLE:
#include<<iostream.h> Void main ( { Float x=100; Float & y=x; Cout<< x=<<x<<end1<< y=<<y; Y=10 Cout<< x=<<x<<end1<< y=<<y; )

NOTE: & is not a address operator , here notation float & means reference to float. If the value of any variable changed, it will be assigned to both variables, so the first cout statement will display 100 for both variables and next cout statement will display 10.

OPERATORS IN C++
All c operators are valid in c++, some new operators are also introduced. We have already seen two operators, insertion operator (<<) and extraction operator (>>). Some new operators are:

SCOPE RESOLUTION OPERATOR ( : : )


Suppose in a c++ program global variable and the local variable has same name x , now if we want to access the variable in the function, we always access the local variable. This is because according to the rule the local variable gets priority on global variable, so a global variable remains unaccessible when a local variable of same name is present. Thus to access the global variable in such circumstances Scope Resolution Operator is used.

EXAMPLE:
#include<iostream.h> #include<conio.h> Int x=10; { Clrscr ( ) ; Int x=20; Cout<< local=<<x; //clears the screen //local variable //displaying local variable //global variable

Cout<<end1; Cout<< global=<< : :x ; //displaying global variable X=50; Cout<< local=<<x; Cout<<end1 ; Cout<< global=<< : : x ; Getch ( ) ; }

//blank line

//value change in variable.

//press any key

NEW AND DELETE OPERATOR


The new operator is used to create memory space for any valid data type and user defined data types such as arrays, structures, classes.

SYNTAX:
Pointer available = new data type; The delete operator works opposite of new operator, it destroys the object to the release the memory space for reuse.

SYNTAX:
Delete pointer variable ;

Example:
#include<conio.h> #include<iostream.h> #include<strinh.h> Void main ( ) { Clrscr ( ) ; Char *n= shekhawati senior secondary school losal ; Int len =strlen (n) ; Char *ptr ; Ptr =new char [len] ; Strcpy (ptr, n) ; Cout<<ptr; Delete ptr ; Getch ( ) ; }

TYPECASTING
C++ allows type conversions of variables or expressions.

Example:
#include<iostream.h> #include<conio.h> Void main ( ) { Clrscr ( ) ; Float x=10.78; Cout <<x ; Int y=float (x) //assigning float value in integer variable. Cout<<end1 ; Cout<<y; Getch ( );

Chapter 4 FUNCTIONS

Functions are the major feature of structured programming.


Functions are used to divide a complex program into parts and each part performs a specified task so that its size can be reduced. These function can be called whenever required at different places in the program.

Function Prototype
Function prototype is the declaration that defines both: (i). Arguments passed to the function and (ii). The type of value returned by the function. The compiler uses this prototype to check whether the types of arguments passed in a function call are the same as they are mentioned in the prototype or not.

Syntax:
Type function name (argument list); Float add (float x, float y);

Note:

argument list contains the types and names of the

arguments that must be passed to the function.

Calling a Function
A function can be called in two ways:

1. Call by value
Function creates a new set of variables and copies the values of arguments in to them, and doesnt access the actual value of the passed variables.

2. Call by reference
If we want to alter the values of variables, it can not be possible in call by value mechanism. If we pass parameters by reference at that time the variable in argument list becomes alias of the actual variable in the calling statement. It means when the function is working on the parameters indirectly it is working on the actual variable.

Example:
#include<conio.h> #include<iostream.h> Void swap ( int *a, int *b) ; //function prototype. Void min ( ) { Clrscr ( ); Int x;y; Cout<< Enter value of x:; Cin>>y; Swap (&x, &y); // calling a function by reference.

Cout<< value of x is:<<x<<end1 ; Cout<< value of y is:<<y<<end1 ; Getch ( ); Void swap (int *a, int *b) { Int t ; T= *a; *a= *b; *b= t; //function declaration

Note:void functions are those functions that do not return any


value.

INLINE FUNCTIONS
An inline function is a function that is expanded in line when it is invoked, means the compiler replaces the function call with the corresponding function code. Inline functions are written like a normalfunction but we have to declare these function with a prefix inline. NOTE: in line functions make a program run faster and save memory space because the statement that defines the inline function is reproduced at each point where the function is called.

SYNTAX:
Inline function- header { Function body; }

Example:
#include<iostream.h>

#include<conio.h>

Inline float div (float x, float y) { Return x/y; } Inline float mul (float x , float y) { Return x*y } Void main ( ) { Float a,b; Clrscr ( ); Cout << \nEnter 2 nos :; Cin >>a; Cin >>b; Cout << \nMultiplication =<<mul (a, b); Cout << \n Div = <<div(a, b); Getch ( );

Function Overloading
Overloading refers to use the same thing for different purposes, this is known as polymorphism in OOP. Function overloading means that we can use the same function name to create several functions that perform different task. In other words an overloaded function appears to perform different activities depending on the kind of data sent to it. Overloaded functions have same names even though they have different arguments. Overloaded functions can simplify the programmers life by reducing the number of function names to be remembered. Complexity arises when overloading is not used.

Example:
#include<conio.h> #include<iostream.h>

Int square (int x); Float square (float x); //prototype of overloaded function

Void main ( ) { Clrscr ( ); Int a=10 Float b=3.3; Cout<< square of a is :<<square (A)<<end1; // function call Cout << square of b is :<<square(B); //function call Getch ( ); } Int square (int x) { Return x*x; } Float square (float y) { Return y*y; } //function declaration //function declaration

Exercise:
1. Write a function power ( ) that takes double value for m and int value for n and return the m raised in power of n. write an other function with same name which takes int value for m and double value for n. call both function in main ( ). 2. Create three functions name volume to find volume of a cube, cylinder and rectangular box. Formulas for the volumes of the three shapes are: (i)For cube volume =size*size*size (ii)For cylinder volume =3.141*(r*r) (iii)For rectangular box volume =l*b*h 3. Create an overloaded function that will convert a character into ASCII number, and a number into ASCII value.

Chapter 5 Classes and Objects

A class is a way to bind the data and its associated functions together. It hides the data from external use. Binding the data and the functions together into a class is called as encapsulation. General syntax of class declaration: Class class_name

{ Private: Variable declarations; Function declarations; Public: Variable declarations; Function declarations; }; Class declaration is same as structure declaration in c, but in classes we can also declare member functions. Keyword class specifies that follows an user defined data of type class name. the class body is enclosed in braces and contains the declaration of variables and functions. These functions are called as member functions and the variables are known as data members. Collectively they are called as members. The members are grouped under two sections, these sections are called as visibility labels. The sections are:

(1). PRIVATE SECTION:


The members that have been declared as private can be accessed only within the class; it fulfills a key feature of OOP, Data hiding. The private section is optional means by default the members of a class is private. If the both labels are missing then the member are considered as private.

(2). PUBLIC SECTION:


The members that have been declared as public can be accessed from outside of class also.

Example:
Class student { Private: Char name [20]; Int roll_no, marks; Public: Void accept (void); Void display (void); };

Creating objects (variables)


Once a class has been declared, we can create variables of class type by using the class name (like any built type variable).

Example:
Student a, b, c; The other way of creating variables of class type is by placing the variable name immediately after closing braces of class.

Example:
Class student { Class members; } a, b, c;

Accessing class members


The private members of a class can be accessed only through member functions of that class. The public members can be accessed by the objects directly. By following format the main ( ) can access the member functions.

Syntax:
Object_name. Function name (arguments);

Example:
a.accept ( ); a.display ( );

Defining member functions


Member functions can be defined in two ways: (i). Outside class

Syntax:
Return_type class_name :: Function_name (parameters) { function body ; } The label class_name : : tells the compiler the function belongs to the class specified by that class_name. and the scope of the function is restricted to members of the class specified. NOTE: : : is known as scope resolution operator.

Example defining function outside class


#include<conio.h> #include<iostream.h> Class student { Private: Char name [20]; Char roll_no, marks; Public: Void //declaring members in public sec. accept (void); //function. //declaring members in private sec. //declaration of class

Declaration. Void display (void); //function

Declaration }; // defining member functions outside the class through scope resolution operator (: :). Void student : :accept (void) { Cout<< Enter roll no. of student :; Cin>>roll_no;

Cout<< Enter name of student :; Cin>>name; Cout<< Enter marks of student :; Cin>>marks; } Void student : :display (void) Cout<< Name of student : <<name<<end1 ; Cout<< Roll no. of student : <<roll_no<<end1; Cout<< marks of student : <<marks; Void main ( ) { Clrscr ( ); Student a; //creating object of class type.

// calling function through object a. Accept( ); a. Display ( ); Getch ( ); } (ii) Inside class

Another way of defining the member function is to replace the function declaration by the function definition in the class.

Example:
#include<conio.h> #include<iostream.h> Class student { Private : Char name [20]; Char roll_no, marks ; Public: //function declaration and definition Void accept (void) { Cout<< Enter roll no. of student :; Cin>>roll_no Cout<< Enter name of student :; Cin>>name; Cout<< Enter marks of student :;

Cin>>marks; } Void display (void) { Cout<< Name of student : <<name<<end1; Cout<< Roll no. of student : <<roll_no<<end1; Cout << marks of student : <<marks; } A; //variable/ object declaration of class student. Void main ( ) Clrscr ( ) Student a; a.accept ( ); a.display ( ); getch ( ); }

Private member function


Some time you want to hide some function from outside calls, at that time functions are declared in private section.

A private function can only be called by another function that is a member function of related class. Even an object can not invoke a private function. EXAMPLE: #include<iostream.h> #include<conio.h> Class great { Private: Int m, n; Int largest (void) { If (m>=n) Return m; Else Return n; } Public: Void accept ( ); Void display ( ); //declaring private function

}a; Void great : :accept (void) { Cout << Enter value of m:; Cin>>m; Cout<< Enter value of n:; Cin>>n; } Void great : :display (void) { Cout<< largest number is : <<largest ( ); //calling private function. } Void main ( ) { Clrscr ( ); a.accept ( ); a.display ( ); getch ( ); }

Nesting member function


A member function can be called in another member function of the same class. This is known as nesting of member function. Above example can also be treated as a nesting of member functions.

EXAMPLE: #include<iostream.h> #include<conio.h> Class great { Private: Int m, n; Public: Int largest ( ); Void accept ( ); Void display ( ); }a; Int great : :largest (void) { If (m>=n)

Return m; Else Return n; } Void great : :accept (void) { Cout<< Enter value of m:; Cin>>m; Cout<< Enter value of n:; Cin>>n; } Void great : :display (void) { Cout<< largest number is:<<largest ( ); //nesting of member function. } Void main ( ) { Clrscr ( ); a.accept ( );

a.display ( ); getch ( );

Arrays of objects
We can declare an array of any built in type , similarly we can also have an array of type class. Such variable are called as array of objects. EXAMPLE: #include<conio.h> #include<iostream.h> Class employee { Char name [20]; Int age; Float sal; Public: Void accept ( ); Void display ( ); }; Void employee : :accept ( ) {

Cout<< Enter name :; Cin>>name; Cout<< Enter age :; Cin>>age; Cout<< Enter salary:; Cin>>sal; } Void employee: :display ( ) Cout<< name :<<name<<end1; Cout<< age :<<age<<end1; Cout<< salary :<<sal; } Void main ( ) { Clrscr ( ); Employee emp [3]; // array of class type. For (int i=1; i<=3; i++) { Cout<< Enter details of employee :<<1<<end1; Emp [i]. accept ( );

} For (i= 1; i<=3; i++) { Cout<< details of employee :<<i<<end1; Emp [i]. display ( ); } Getch ( ); }

Constructors
A constructor is a special member function whose purpose is to initialize the objects of its class. Constructors name is same as the class name. It is invoked automatically whenever an object is created. It is called constructor because it construct the values of the data members of its class.

EXAMPLE: #include<iostream.h> #include<conio.h> Class counter {

Private: Int count; Public: Counter ( ) { Count=0; } Void inc_count ( ) { Count ++; } Int get_count ( ) { Return count; }; Void main ( ) Counter c1, c2; Clrscr ( ); Cout << \ncl =<<c1.get_count ( ); //display Cout<< nc2 = <<c2.get count ( ); //return count //constructor

C1. inc_count ( ); C2. Inc_count ( ); //display again

//increment of counter

Cout<< \nc1.get_count ( ); Cout<< \nc2 =<<c2.get_count ( ) Getch ( ); }

Destructor
A destructor as the name suggests is used to destroy the objects that have been created by the constructor. Like a constructor the destructor is also a member function whose name is same as class name, but prefixed by a title (~) sign. A destructor never accepts any arguments not return any value. It is a good practice to declare destructors since it releases memory space for future uses. EXAMPLE: #include<conio.h> #include<iostream.h> Class alpha {

Int count; Public: Alpha ( ) Definition { Count=0; Count++; //initialization //increment //constructor

Cout<< no. of objects created.<<count; } ~alpha( ) Definition { Cout<< no. of objects destroyed:<<count; } }; Void main ( ) { Clrscr ( ); Alpha al; Getch ( ); //declaring object //destructor

Friend function
A friend function is a function that, although not a member of that class, but has full access rights to the private members of the class. Friend functions are declared with the keyword friend. But in all other aspects, the friend is a normal function in terms of scope, declarations and definitions.

Characteristics of friend function


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, so it cannot be called using the objects of that class. It can be invoked as normal function. Like member function, it cannot access the members directly and has to use object and dot operator to access each member. It can be declared in either public or private section.

EXAMPLE: #include<iostream.h> #include<conio.h> Class sample

{ Int a; Int b; Public: Void set value ( ) A=25; B=40; } Friend float means (sample s); //FRIEND declared. }; Float means (sample s) { Return float (s.a+s.b)/2.0; } Void main ( ) { Sample X; X.set value ( ); Clrscr ( ); //calling friend //defining friend function.

Cout<< \mean value=<<mean(X); Getch ( ); }

EXAMPLE: FRIEND FUNCTION OF TWO CLASSES. #include<conio.h> #include<iostream.h> Class one; //pre declaration of class. Class two { Int b; Public: Void accept ( ); // friend function of class one and two Friend void max_num(one, two); }; Class one { Int a; Public:

Void accept ( ); Friend void max_num( one, two); }; Void one :: accept ( ) { Cout<< Enter value of a for class1 :; Cin>>a; } Void two: :accept ( ) { Cout<< Enter value of b for class2:; Cin>>b; } //defining friend function Void max_num(one x, two y) { If (x.a>=y.b) Cout<<x.a; Else Cout<<y.b; }

Void main ( ) { One o; Two p; o.accept ( ); p.accept ( ); max_num (o,p); Getch ( ); } //calling friend function.

Example 2: #include<conio.h> #include<iostream.h> Class one; //forward declaration Class two { Int b; Public: Void accepts ( ); Void display ( );

//friend function for class one and two. Friend void exchange (one &, two &); }; Class one { Int a; Public: Void accepts ( ); Void displays ( ); Friend void exchange (one &, two &); }; Void one: :accept ( ) { Cout<< Enter value of a for class 1: Cin>>a; } Void one: :display ( ) { Cout<< value of a:<<a; }

Void two: :accept ( ) { Cout<< Enter value of b for class2:; Cin>>b; } Void two: :display ( ) { Cout<< value of b:<<b; } Void exchange (one &x, two &y) { Int temp=x.a; x.a=y.b; y.b=temp; } Void main ( ) { Clrscr ( ); One obj_1; Two obj_2;

//accepting values for the private variables. Obj_1.accept ( ); Obj_2.accpt ( ); Cout<< values before exchange.\n; Obj_1.display ( ); Cout<< \t; Obj_2.display ( ); Exchange (obj_1, obj_2); Cout<< \n; Cout<< values after exchange.\n; Obj_1.display ( ); Cout<< \t; Obj_2.display ( ); Getch ( ); } //swapping of values.

Operator overloading
Operator overloading is one of the many exciting features of c++ language. C++ has the ability to provide operators a special meaning for a data type. This mechanism of giving special features to an operator is known as operator overloading.

Operator overloading provides flexibility for creating new definitions for most of the c++ operators except following operators: (1). Dot operator (.) (2). Scope resolution operator (: :) etc. NOTE: we can almost create a new programming language by creative use of function and operator overloading techniques. NOTE: when an operator is overloaded, its original meaning is not lost. For example, + operator, which is overloaded can still be used to add two numbers.

Defining overloaded operator


Operator can be overloaded by special function, called operator function.

SYNTAX:
Return_type class name: : operator op(argulist) { Function body; } Return_type is the type of value returned by the operation, and op is the operator being overloaded.

Operator overloading is of two types: (1). Unary operator overloading

Example 1: unary (member) operator function


In unary operator overloading data is passed implicitly hence there is no argument passed to the function. #include<conio.h> #include<iostream.h) Class abc { Int x; Public: Void accept ( ) { Cout<< Enter value of x:; Cin>>x; } // declaring unary + operator member function Void operator + ( ); }; // defining unary + operator function

Void abc: :operator + ( ) { X+=2 Cout<<x<< \n; } void main ( ) { Clrscr ( ); Abc z; z.accept ( ); for (int i=1; i<=10; i++) +z; } //invoking unary + operator getch ( );

Example 2: Unary (friend) operator fuction


If operator function is a friend function data is passed explicitly hence there is one argument passed to the function, and argument passed by reference. #include<conio.h> #include<iostream.h>

Class abc { Int x; Public: Void accept ( ) { Cout<< x=; Cin>>x; } //declaring unary + operator friend function Void friend operator + (abc); }; //defining unary + operator friend function Void operator + (abc & a) { a.x+=2; cout<<a.x<< \n; } Void main ( ) {

Clrscr ( ); Abc z; z.accept ( ); for (int i=1; i<=10; i++) +z; Getch ( ); } //invoking unary + operator

(2). Binary operator overloading


EXAMPLE 1: BINARY (MEMBER) OPERATOR FUNCTION In case of binary member function first object is passed implicitly while second is passed explicitly, hence there is one argument. #include<conio.h> #include<iostream.h> Class abc { Private: Int a, b Public: Void accept ( );

Void display ( ); //declaring unary * operator member function Abc operator * (abc); }; Void abc: :accept ( ) { Cout<< Enter value of a:; Cin>>a; Cout<< Enter value ofb: ; Cin>>b; } Void abc: :display ( ) { Cout<< value of a:<<A<< \n ; Cout<< value of b: <<b<< \n; } //defining unary * operator member function abc abc: : operator * (abc x) { Abc temp;

Temp.a=a+x.a; Temp.b=b+x.b; Return temp; } Void main ( ) { Clrscr ( ); Abc x, y, z; x.accept ( ); y.accept ( ); z=x*y; //invoking binary * operator

z.display ( ); getch ( ); }

Example 2: Binary (friend) operator function In case of binary friend operator function both objects are passed explicitly hence there are two arguments passed. #include<conio.h> #include<iostream.h>

Class abc { Private: Int a,b; Public: Void accept ( ); Void display ( ); Abc friend operator (abc, abc); }; Void abc: :accept ( ) { Cout<< Enter value of a:; Cin>>a; Cout<< Enter value of b:; Cin>>b; } Void abc: :display ( ) { Cout<< value of a: <<a<< \n; Cout<< value of b:<<b<< \n;

} Abc operator (abc x, abc y) { Abc temp; Temp. a= x.a+y.a; Temp. b=x.b+y.b; Return temp; } Void main ( ) { Clrscr ( ); Abc x, y , z; x.accept ( ); y.accept ( ); z=operator (x, y); z.display ( ); getch ( ); }

Chapter: 6 INHERITENCE

C++ strongly supports the reusability of codes. This can be basically done by creating new classes and reusing the properties of existing classes in the new class. The mechanism of deriving a new class from an existing class is called as inheritance. The new class is called as derived class, and old class is called as base class. A derived class inherits some or all properties of the base class.

Defining derived class


A derived class is defined by specifying its relationship with the base class in addition to its own properties.

SYNTAX: Class derived_class_name : visibility_label base class_name { Members of derived class; }

The colon ( : ) indicates that the derived class is derived from base class. The visibility label is optional and, if present, maybe either public or private. By default label is private. Visibility labels specifies that whether the features of the base class are privately derived or publically. If derived class privately inherits base class then the public members of the base class becomes private members of the derived class, and can be access by the member function of the derived class. If derived class publically inherits base class then the public members of base class become public members of the derived class, and therefore they are accessible to the objects of the derived class.

(1). SINGLE INHERITENCE Class a..>class b Base class derived class

Example: Public inheritance #include<conio.h> #include<iostream.h> Class a { Int a, b ; Public: //private not inheritable. //base class definition

Int c; Void get data ( ) { Cout<< enter value of a:; Cin>>a; Cout<< enter value of b:; Cin>>b; } Void add ( ) { C=a+b; } }; Class b : public a { Public: Void print ( ) { Cout<< value of c is:<<c; } //deriving class as public.

}; Void main ( ) { Bx; x. get data ( ); x. add ( ); getch ( ); } NOTE:in inheritance the object of the derived class is used to call the member function of both derived class as well as base class. Example: privately inheritance #include<conio.h> #include<iostream.h> Class a { Int a, b; Public: Int c; Void get data ( ) { //object of derived class.

Cout<< enter value of a:; Cin>>a; Cout<< enter value of b:; Cin>>b; } Void add ( ) { C=a+b; } }; Class b : private a { Public: Void print ( ) { Get data ( ); Add ( ); //calling private function //calling private function. //deriving class as public.

Cout<< value of c is:<<; } };

Void main ( ) { Bx; x. print ( ); getch ( ); //object of derived class. //calling public function

Protected Section
In both above examples the derived class cannot access the private members of the base class. To inherit the private members of the base class we need to declare the private numbers as protected. After doing this they can be accessed by the member function of the derived class. Example: applying protected section #include<conio.h> #include<iostream.h> Class a { Protected: Int a, b, c; Public: Void get data ( )

{ Cout<< enter value of a:; Cin>>a; Cout<< enter value of b:; Cin>>b; } }; Class b : public a { Public: Void add ( ) { C=a+b; } Void print ( ) { Cout<< value of c is: <<c; } }; Void main ( )

{ B x; Clrscr ( ); x. get data ( ); x. add ( ); x. print( ); getch ( );

(2). Multilevel Inheritence


Grandfather Class a> Base class father class b> intermediate base class son class c derived class

The class b is known as intermediate base class because it provides a link for the inheritance between a and c. the chain abc is known as inheritance path. Example: #include<conio.h> #include<iostream.h> Class a //defining base class

{ Protected: Int a, b; Public: Void accept ( ); }; Class b : public a { Protected: Int c; Public: Void add ( ); }; Class c : public b { Public: Void print ( ); }; Void a: :accept ( ) { //derived class //intermediate base class

Cout<< enter value of a:; Cin>>a; Cout<< enter value of b:; Cin>>b; } Void b: : add ( ) { C=a+b; } Void c: :print ( ) { Cout<< value of c:; } Void main ( ) { Cx; Clrscr ( ); x.accept ( ); x.add ( ); x.print ( ); //object of derived class.

getch ( ); }

(3). Multiple inheritance


When a new class is derived from more than one class, this type of inheritance is known as multiple inheritances. CLASS B1..>BASE CLASS1

CLASS B2..> Base class2

CLASS D <CLASS B3 derived class base class3

Example: #include<conio.h> #include<iostream.h> Class a { Protected: Int a; Public:

Void get_a( ); }; Class b { Protected: Int b; Public: Void get_b ( ); }; Class c : public a, public b { Int c; Public: Void add ( ); Void print ( ); }; Void a: : get_a ( ) { Cout<< enter value of a:; Cin>>a;

Void b: :get_b ( ) { Cout<< enter value of b:; Cin>>b; } Void c: :add ( ) { C=a+b; } Void c: :print ( ) { C=a+b; } Void c: :print ( ) { Cout<< value of c:<<c; } Void main ( ) { C x;

Clrscr ( ); x.get_a ( ); x.get_b ( ) x.add ( ); x.print ( ); getch ( ); }

Virtual base class


A base class that has been defined as virtual in the inheritance path. In multiple inheritances, a derived class can inherit the members of a base class via two or more inheritance paths. If the base is not virtual, the derived will inherit more than one copy of its members will be inherited to the derived class by ignoring the number of inheritance paths. GRAND PARENTS FATHER SON In above example the son class will inherit the members of the grandparent class twice, first via father class and second via mother class. This means the child class would have duplicate sets of the members of grandparent class. This can be avoided by making the common class as virtual base class. MOTHER

EXAMPLE: #include<iostream.h> #include<conio.h> Class student { Protected: Int r_no; Public: Void get_rno ( ) { Cout<< Enter roll number:; Cin>>r_no; } Void put_rno ( ) { Cout<< roll number:<<r_no<< \n; } }; Class test: virtual public student {

Protected: Float marks_1, marks_2: Public: Void get_marks ( ) { Cout<< Enter marks 1:; Cin>>marks_1; Cout<< Enter marks 2:; Cin>>marks_2; } Void put_marks ( ) { Cout<< Total marks obtained\n; Cout<< Marks1:<<marks_1<< \n; Cout<< Marks2:<<marks_2<< \n; } }; Class sports: virtual public student { Protected:

Float score; Public: Void get_score ( ) { Cout<< Enter score:; Cin>>score; } Void put_score ( ) { Cout<< score:<<score<< \n; } }; Class result: public test, public sports { Float total; Public: Void display ( ); }; Void result : : display ( ) {

Total=marks_1+marks_2+score; Put_rno ( ); Put_marks ( ); Put_score ( ); Cout<< total score :<<total<< \n; } Void main ( ) { Clrscr ( ); Result stud_1; Stud_1.get_rno ( ); Stud_1.get_marks ( ); Stud_1.get_score ( ); Stud_1.display ( ); Getch ( ); }

Abstract class
An abstract class is a class that serves only as a base class from which two classes are derived. An abstract class is not used to create any objects. In above example the student class is an abstract class since it was not used to create any objects.

Chapter: 7 Graphics with c++


When the computer is booted, it is always in the text mode. And the screen is divided into 25 rows and 80 columns. In graphics mode a single dot, which is called a pixel is used for display.

System coordination
The screen is considered having x-axis and y-axis. The upper left hand corner is considered as 0,0 for x-axis and y-axis. The maximum value of x-axis is 639 and y-axis is 479.

Getmaxx ( )
Getmaxx ( )returns the maximum x-axis value related to the screen for the current graphics driver and mode. Returns 639.

Getmaxy ( )
Getmaxy ( ) returns the maximum y-axis value related to the screen for the current graphics driver and mode. Returns 479.

Initializing graphics system


C++ provides a function initgraph ( ) for changing the system mode from text to graphics. Initgraph initializes the graphics system by loading a graphics driver from disk then putting the system into graphics mode. Syntax: Void initgraph (int *graph driver, int *graph mode, char path); *Graphdriver integer that specifies the graphics driver to be used. You can use detect to let the system to auto check the display driver. *graphmode integer that specifies the initial graphics mode if *graphdriver is not set to detect. If graphdriver detect, initgraph sets *graphmode to the highest resolution available for the detected driver. *path specifies the directory path where initgraph looks for graphics driver first. Closing graphics system When the graphics system is not required then the screen should be switched back to the text mode using closegraph ( ) function.

Syntax: Void closegraph ( ); Other functions *Line ( ) Line ( ) draws a line from ( x1, y1) to (x2, y2) using the current color, line style, and thickness. Syntax: Line ( int x1, int y1, int x2, int y2) Example: #include<graphic.h> #include<stdlib.h> #include<stdio.h> #include<conio.h> Void main ( ) { Int a= DETECT, b: // request auto detection Initgraph ( &a, &b, ): // initialize graphics Int xmax=getmaxx ( ); Int ymax=getmaxy ( ); Line (0, 0, xmax, ymax); // draw a line

Line (o, 100, xmax, 100); // draw a line Line (100, 1, 100, ymax); // draw a line Getch ( ); Closegraph ( ); } *setlinesstyle ( ) Thickness and the style of straight lines can be changed using the setlinestyle ( ) function. Syntax: Void setlinestyle (int style, pattern, int thickness) The graphics.h header file defines the following enumerated constants for style: //closing graphics mode.