OBJECT ORIENTED PROGRAMMING (PCC CS 302)

118
GAYA COLLEGE OF ENGINEERING, GAYA OBJECT ORIENTED PROGRAMMING (PCC CS 302) PRABHAT KUMAR CHANDRA ASSISTANT PROFESSOR DEPARTMENT OF COMPUTER SC. & ENGINEERING

Transcript of OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Page 1: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

GAYA COLLEGE OF ENGINEERING, GAYA

OBJECT ORIENTED PROGRAMMING

(PCC CS 302)

PRABHAT KUMAR CHANDRA

ASSISTANT PROFESSOR

DEPARTMENT OF COMPUTER SC. & ENGINEERING

Page 2: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

CONTENTS

1. Scheme

2. Vision of the Department

3. Mission of the department

4. PEO’s and PO’s

5. Course objectives & course outcomes (CO’s)

6. Mapping of CO’s with PO’s

7. Course Syllabus

8. Time table

9. Student list

10. Course Handout

11. Lecture Plan

12. Assignment sheets

13. Tutorial Sheets

14. Sessional Question Papers

15. Old End Semester Exam (Final Exam) Question Papers

16. Question Bank

17. Power Point Presentations

18. Lecture Notes

19. Reference Materials

20. Results

21. Result Analysis

22. Quality Measurement Sheets

a. Course End Survey

b. Teaching Evaluation

Page 3: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Aryabhatt Knowledge University, Patna

Scheme of Teaching & Examination

BE (Computer Science & Engineering) III Semester

scheme

Page 4: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Department of Computer Sc. & Engineering

Vision

Department of Computer science and engineering aims to generate computing

professionals with global outlook and capable of providing leadership in

development of theories products and services for inclusive and sustainable

development of society.

Mission

To impart quality education in theoretical and engineering aspects of

computing.

To train students in practices of computing hardware and software through

laboratory activity.

To cultivate students to incorporate for team spirit, efficient problem solving

skills, better adaptability and good communication skills to become high

professionals

Page 5: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

PEO’s of Computer Sc. & Engineering

Graduates will be capable of attaining higher position in their professional

carrier, capable to do quality research by strengthening their mathematical,

scientific and basic engineering fundamentals.

Graduate will be capable to develop team-spirit, leadership abilities,

collaborative learning, and ethical behaviour.

Graduate will be capable of adopting the changing technologies, tools, and

industrial environment.

Program Outcomes

Engineering Knowledge: Apply the knowledge of mathematics, science,

engineering fundamentals, and an engineering specialization to the solution

of complex Electrical and Electronics engineering problems.

Problem Analysis: Students will be able to identify and analyze real life

problems in order to provide meaningful solutions with the help of acquired

knowledge in computer science.

Design/Development of solutions: Students will be able to design cost

effective software/hardware solution, which meets the specific requirement

of the client.

Conduct Investigations of complex problem: Students will be able to

perform testing on the deployed software and analyse the results.

Modern Tool Usage: Students will be able to create, select and apply

appropriate techniques, resources and modern tools to solve existing

scenario, within performance and cost constraint.

The Engineer and Society: Students will be able to understand the

computing needs of inter-disciplinary scientific and engineering disciplines

and design, and develop algorithms and techniques for achieving these.

Environment and sustainability: Students will be able to understand the

software project management principles so that they can work cooperatively,

responsibly, creatively, and respectfully in teams

Individual and team Work: Students will be able to function effectively as

an individual, and as a member or leader in diverse teams.

Communication: Students will be able to communicate effectively in oral,

written and graphical form. They should be able to comprehend and write

Page 6: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

effective reports, design effective presentations, and give and receive clear

instructions.

Project management and Finance: Students will be able to manage

projects in multidisciplinary environments. They should be able to extend

the state of art in some of the areas of interest and create new knowledge.

Life-long Learning: Students will be able to acquire and understand new

knowledge, use them to develop software products, and to understand the

importance of lifelong learning.

Ethics: Students will be able to understand professional and ethical

responsibilities and analyse the impact of computing on individuals,

organizations, and the society.

Program Specific Outcomes:

PSO1: Student will have ability to apply the concepts learn through courses

like Algorithm, data structures, Formal methods and theoretical computer

science to real life mathematical modelling problems and mathematical

research.

PSO2: Student will have ability to apply the concepts learn through courses

like operating system, Artificial intelligence, Database, Networking, Web

Technology and programming languages to software developments.

PSO3: The ability to lead and work in a team with good communication,

project management and documentation skills

Page 7: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Course Objectives

Understand object-oriented programming features in C++,

Apply these features to program design and implementation,

Understand object-oriented concepts and how they are supported by C++,

Understand implementation issues related to object-oriented techniques,

Build good quality software using object-oriented programming technique.

Course Outcomes

CO1 Student will able to understand the concept of Variables, data Types

(including strings and arrays) , expressions and flow control.

CO2 Student will able to understand the concept of functional and procedural

abstraction and its importance in good program design.

CO3 Student will able to analyse a simple programming problem specifications.

CO4 Student will able to design a high-level (programming language

independent) solution to the problem using functional abstraction and general

imperative programming language constructs.

CO5 Student will able to write, compile, execute and debug a C++ program which

maps the high-level design onto concrete C++ programming constructs.

Page 8: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Course Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 √ √

CO2 √ √ √

CO3 √ √ √

CO4 √ √ √ √

CO5 √ √ √ √

Page 9: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Syllabus

Module 1 Lecture: 3 hrs. Introduction to C++ : Object Oriented Technology, Advantages of OOP, Input- output in C++, Tokens, Keywords, Identifiers, Data Types C++, Derives data types. The void data type, Type Modifiers, Typecasting, Constant, Operator, Precedence of Operators, Strings. Module 2 Lecture: 6 hrs. Control Structures and Functions: Decision making statements like if-else, Nested if-else, goto, break, continue, switch case, Loop statement like for loop, nested for loop, while loop, do-while loop. Parts of Function, User- defined Functions, Value- Returning Functions, void Functions, Value Parameters, Function overloading, Virtual Functions. Module 3 Lecture: 12 hrs. Classes and Data Abstraction : Structure in C++, Class, Build- in Operations on Classes, Assignment Operator and Classes, Class Scope, Reference parameters and Class Objects (Variables), Member functions, Accessor and Mutator Functions, Constructors, default Constructor, Destructors. Module 4 Lecture: 8 hrs. Overloading, Templates and Inheritance: Operator Overloading, Function Overloading, Function Templates, Class Templates. Single and Multiple Inheritance, virtual Base class, Abstract Class, Pointer and Inheritance, Overloading Member Function. Module 5 Lecture: 11 hrs. Pointers, Arrays and Exception Handling: Void Pointers, Pointer to Class, Pointer to Object, Void Pointer, Arrays. The keywords try, throw and catch. Creating own Exception Classes, Exception Handling Techniques (Terminate the Program, Fix the Error and Continue, Log the Error and Continue), Stack Unwinding

Text Books:

1. Thinking in C++, Volume 1 & 2 by Bruce Eckel, Chuck Allison, Pearson Education 2. Mastering C++, 1/e by Venugopal, Tata McGraw Hill. 3. Object Oriented Programming with C++, 3/e by E. Balaguruswamy, Tata McGraw Hill. 4. Starting Out with Object Oriented Programming in C++, by Tony Gaddis, Wiley India.

Reference Books: 1. The C++ Programming language 3/e by Bjarne Stroustrup, Pearson Education. 2. C++, How to Programme, 4e, by Deitel, Pearson Education. 3. Big C++ by Cay Horstmann, Wiley India. 4. C++ Primer, 3e by Stanley B. Lippmann, Josee Lajoie, Pearson Education. 5. C++ and Object Oriented Programming Paradigm, 2e by Debasish Jana, PHI. 6. Programming with C++, 2/e by Ravichandran, Tata McGraw Hill. 7. C++ Programming Black Book by Steven Holzner, Dreamtech Press.

Page 10: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Time- Table:

Page 11: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Detailed Teaching Plan

Lecture No.

Unit No. Topics To Be Covered

1 1 Basic concepts of OOP

2 1 Benefits of OOP, Object Oriented Language, Structure of C++ Program

3 1 Operators & Expressions

4 1 Operators & Expressions

5 2 Looping concepts

6 2 Arrays & Structures

7 2 Functions

8 3 Specifying a class, Define member function, Scope of class and its member

9 3 Data hiding & encapsulation

10 3 Friend function

11 3 Friend function

12 3 Array within a class

13 3 Static data member, static member function

14 3 Constructor function, default constructor

15 3 Parameterized multiple constructor, copy constructor

16 3 Destructor function

17 3 Function overloading

18 3 Operator overloading

19 3 Operator overloading

20 3 Data conversion between objects of different classes

21 4 Define derived classes, single inheritance

22 4 multilevel inheritance

23 4 Hierarchical inheritance, Hybrid Inheritance

24 4 Pointers to objects

25 4 this pointer

26 4 Pointers to derived class

27 4 Virtual function

28 4 Pure Virtual function, Abstract class

29 3 Accessor and Mutator Functions

30 4 Introduction to Templates

31 4 Introduction to Templates

32 5 Exception, Creating and handling

33 5 Exception, Creating and handling

34 5 Templates and Exception in OOP

35 5 Static Unwinding

36 Revision

Page 12: OBJECT ORIENTED PROGRAMMING (PCC CS 302)
Page 13: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

CSE Student List(ROLL NO. WISE) Registration No. Name

18105110018 Abhishek Kumar

18105110020 RAMAVTAR KUMAR

18105110025 Somiya rani

18105110033 Subrat Pandey

18105110042 SURABHI KUMARI

18105110049 Gaurav kumar

19105110002 Md Kashif

19105110003 SHALU KUMARI

19105110004 Rupesh Kumar

19105110005 Nitesh Kumar Gond

19105110006 Nitesh Kumar Pritam

19105110007 Simran Mehandi Patel

19105110008 Ashmit Kumar

19105110009 Vikash kumar

19105110010 Ranjan Kumar

19105110011 Atul Kirti

19105110012 Shivam Kumar

19105110013 Pawan Prakash

19105110014 Shreeram Kumar Singh

19105110015 Manjit Patel

19105110016 Abhishek Kumar

19105110017 Ankit kumar

19105110018 [email protected]

19105110019 ABHIRANJAN KUMAR

19105110021 Kundan Kumar

19105110022 Aditya Nandan

19105110023 Saima Parween

19105110024 Ritu Raj

19105110025 Rahul Kumar

19105110026 Sumit raj

19105110027 NIKESH PANDIT

19105110028 Anshu Pandey

19105110029 RAVI KANT

19105110030 Hritu Kumari

19105110031 Nitesh Kumar Gupta

19105110032 Komal Kumari

19105110034 Hasan Raza

19105110035 Amit Kumar

19105110037 Bipul kumar

19105110039 Sonu Kumar

19105110041 Gautam Kumar

19105110043 Praveen Kumar gupta

19105110044 MD OZAIR QAYAM

19105110045 Abhinav kumar Rajak

19105110046 Suhani kumari

19105110047 ANKIT KUMAR

19105110048 Arpita jha

19105110049 PRADUMAN KUMAR

19105110050 Shambhu Kumar

19105110051 SREYANSH RAJ

19105110052 Surbhi kumari

Page 14: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

19105110053 Anish Kumar

19105110054 Praveen Kumar

19105110056 Md sahil khan

19105110057 Vinita kumari

19105110058 Dimpal Yadav

19105110060 Navneet raj

19105110061 Tulsi Aakanksha

19105110062 Raj nayan

Page 15: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Class Notes

History Of The C++: C++ is an Object Oriented Programming laguage.It was developed by

Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill New Jersy, USA, in early 1980’s.

C++ is an extension of C with major addition of the class construct feature.

Stroustrup initially called the new language’C with Classes.

In 1983 the name was changed to the C++.

C++ is superset of the C.

Programming paradigms:

Programming paradigms means the way of writing a program depending upon the requirements.

These requirements mainly focus the task of development team to develop programs for the

small-scale projects to the large-scale projects. The programming paradigms is categorized into

the following way

2. Procedural programming

3. Structural programming

4. Object oriented programming

Procedural programming:

In the procedural programming approach the problem is divided into sequence of functions. The

primary focus in this approach is on functions. Number of functions are written to accomplish the

task of a project. In a multifunction program important data items are placed as global data and

they may be accessed by all the functions. Each function is also having a set of local data items.

The following are the important features:

1. Programs are organized in the form of subroutines and all data items are global

2. Program control achieved by call to subroutines

3. Code reusability occurs

4. Suitable for medium sized software application

5. Difficult to maintain and enhance the program code

The drawback is there is no data security for global data.

Global data

F1 F2 F3 F4

Local Local Local Local data data data data data data data

Page 16: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Advantages of procedural programming include its relative simplicity, and ease of

implementation of compilers and interpreters.

Examples of procedural programming languages include FORTRAN, ALGOL, Pascal, C,

MODULA2, Ada, BASIC.

Structured programming

Structured programming is used to develop large-scale projects. The large-scale project consists

of large development team, developing different parts of the same project independently. The

separately compiled program modules are grouped together to create big projects. In this multiple

module program, each module is having a separate set of related functions. The following are

important features of structured programming

3. Importance given to algorithm rather than data

4. Projects can be broken up into modules and programmed independently

5. Each module is divided into individual procedures that perform separate tasks.

6. Module are independent of each other as far as possible

7. Modules have their own local data and processing logic

8. User defined data types are introduced.

Object oriented programming: OOP is a method of implementation in which programs are

organized as co-operative collections of objects, each of which represents an instance of some

class and whose classes are all members of a hierarchy of classes united through the property

called inheritance.

Object A Object B

Communication

Object based language = encapsulation + object identity

Object oriented language = object based + inheritance + polymorphism

Global data

M1

Module 2 F1 F2

M3

Data

Function

Data

Function

Data

Function

Page 17: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Object oriented programming is an extension for the basic structured programming

language. In this technique more importance is given to the data. Using this technique we

can combine data as well as operations that can be performed on data as a single unit using

“Class data type”.

Benefits of OOP

1. Implementing Reusability by making Reusable Classes and creating Objects from those

Classes.

2. Providing various levels of Data protection and hiding by using Public, Private and Protected

access specifiers.

3. Providing Protection to Data and Functions both.

4. Helps in creating Flexible, Extensible and Maintainable code.

5. Effective solutions for Real World problems by implementing Classes representing Real

World Entities.

6. Quick software development due to Reusability and easy implementation of Real World

Entities and their Relationships using Inheritance.

The following are the important features of object-oriented programming.

Importance given to data rather than algorithm

Data abstraction is introduced in addition to procedural abstraction.

Data and associated operations are unified into a single unit

The objects are grouped with common attribute operation and semantics.

Programs are designed around the data being operated rather than operate themselves.

Relationships can be created between similar, yet distinct data types.

Difference between Procedural Programming and Object Oriented Programming

No Procedural Programming Object oriented Programming

1 It is a Top-Down approach. It is a Bottom-Up approach.

2 PP basically consists of writing a list of

instructions for the computer to follow, and

organizing these instructions into groups known

as functions.

OOP allows decomposition of a problem

into a number of entities called objects and

then builds data and functions around these

objects.

3 This paradigm is:

“Decide which procedures you

want; use the best algorithms you can find”.

This paradigm is:

“Decide which classes and

objects are needed; provide a full set of

operations for each class”.

4 Languages support this paradigm by providing

facilities for passing arguments to function and

returning values from functions.

Languages support this paradigm by

creating objects and send the messages to

them to use or manipulate the attributes.

5 Importance given to algorithms rather than data. Importance given to data rather than

algorithms.

6 Data move openly around the system from

function to function.

Data cannot move openly around the

system as the concept of data hiding is

involved.

7 E.g. C, COBOL, FORTRAN. E.g. C++, JAVA.

Page 18: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

8 Relationship of data and functions is:

Organization of data and functions in OOP:

Object A Object B

Communication

Object C

9 The primary focus is on functions. The primary focus is on objects.

10 It is suitable for creating medium size projects. It is suitable for creating large size projects.

11 It does not model real world problems very well. It can model real world problems.

12 The complexity of the programs is very high. The complexity of the programs is less.

Top-Down programming

In the top-down design the overall task of the program is to break down a large programs into

several logics and then they are interested by calling these logics whenever necessary.

The top-down approach starts from a high level abstract solution of the given problem and work

down toward more detailed specific solution. In this, the over all task is just defined in terms of

generalized subtask, which are subsequently further, defined and so on. This process is continued

downward until the sub tasks are defined in a form suitable for execution by the computer.

Global Data

Function-1 Local Data

Function-2 Local Data

Data

Functions

Data

Functions

Functions

Data

Complex Problem

Simple Problem1

Simple Problem2

Simple Problem3

Even Simple Problem2

Even Simple Problem1

Page 19: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Advantages

1. It shows the sequential division of the problem from top to bottom, which is a generalized

and easy method.

2. Modules can be developed parallel.

3. Easy, quick and minimum error prone development programs.

Bottom-up Approach

Bottom-up programming is the opposite of top down programming. In bottom up approach all the

subtask are first coded into program and then interacted into increasingly larger modules of the

design, in the bottom up approach available set of modules are first identified. An attempt is made

to combine the lower modules/subprograms to form modules of a high level.

This process of combining modules is continued until the program is constructed. In this

approach quite after it is found that the final program obtained by combining the predetermined

lowest level modules does not meet all the requirement of the desired program.

In a language such as “C++” or “java”, bottom up programming takes the form of constructing

abstract data types.

Advantages

1. The most important modules are written and tested first.

2. It is easier for users or customers to see the progress being made in the project.

3. Testing and debugging are easier and more efficient.

4. The implementation is normally smoother and shorter.

5. Programmer moral and job static function are increased.

6. It is easier to detect and correct time delay and cost average runs.

7. It is easier to deal with time delays and cost overruns when they occur.

8. Data processing resources are used more evenly and efficiently.

Disadvantages

The basic drawback of the bottom up approach is the assumption that the lowest level modules

can be completely specified beforehand, which in reality is seldom possible.

Basic Concepts of Object Oriented Programming

1. Object

2. Class

3. Data Encapsulation and Abstraction

4. Data Hiding

5. Inheritance

6. Polymorphism

7. Dynamic binding

8. Message Passing

1.Object: Objects are the basic run-time entities in an object-oriented system. Programming

problem is analyzed in terms of objects and nature of communication between them. When a

Page 20: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

program is executed, objects interact with each other by sending messages. Different objects

can also interact with each other without knowing the details of their data or code.

1. An Object is an Instance of a Class. An Instance is the existence in the computer system

by acquiring a memory space.

2. An Object is the only way a Class becomes usable.

3. Objects are basis of Object Oriented Programming.

4. An Object has all the Characteristics of the Class using which the Object is created.

5. It implements reusability of code written in Classes.

2. Classes: A class is a collection of objects of similar type. Once a class is defined, any number

of objects can be created which belong to that class. In fact, objects are

variables of the type class. Once a class has been defined, we can create any number of objects

belonging to that class.

1. A Class is a Blueprint or Stencil for creating Objects.

2. A Class specifies all the Member Data and Member Functions that would be present in the

Objects created using the Class.

3. Using a Class any number of Objects can be created.

4. It’s a User Defined Data Type also called Abstract Data Type, which acts like a basic data

type when used.

5. Usually Classes are used to represent computer understandable formats for Real World

Entities.

3. Data Abstraction and Encapsulation

Abstraction refers to the act of representing essential features without including the

background details or explanations. Classes use the concept of abstraction and are defined as a

list of abstract attributes. Storing data and functions in a single unit (class) is encapsulation.

Data cannot be accessible to the outside world and only those functions which are stored in

the class can access it.

Abstraction :-

Object: student DATA Name Date of birth FUNCTIONS Total Average

Page 21: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

1. It’s the process of Hiding the complexities of implementation and providing a simple

Interface for easy use.

2. Its implemented using Encapsulation.

3. Functions, Structures and Classes implement Abstraction at programmer level.

Encapsulation :-

1. It’s the process of wrapping up of Data and Functions inside a single Entity (usually

Classes).

2. Encapsulation helps to establish Abstraction and Data Hiding.

3. Functions, Structures and Classes implement Encapsulation at programmer level.

5. Data Hiding :-

It’s the process of keeping the Data under such an Access mode that its only accessible to

permitted Functions.Using Private, Protected specifiers, we can hide Data from access from

outside a Class. Functions, Structures and Classes implement Data Hiding at programmer

level.

6. Inheritance

Inheritance is the process by which objects can acquire the properties of objects of other class. In

OOP, inheritance provides reusability, like, adding additional features to an existing class

without modifying it. This is achieved by deriving a new class from the existing one. The new

class will have combined features of both the classes.

1. Here the Class which gets the Inherited properties is called the Child Class and from

which it acquires the properties is called the Base or Parent Class.

2. During Inheritance the Protected and Public Data and Functions get passed on as copies

from the Parent or Base Classes to Child Classes.

3. It forms a Hierarchical Structure from Parent down to Children Classes.

4. It implements Reusability of Parent Class Data and Functions.

5. Structures and Classes can be used to implement Inheritance.

6. Types :- Single, Multilevel, Multiple, Hierarchical and Hybrid.

Bird Attributes: Feathers Lay eggs

Page 22: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Fig. Property inheritance

7. Polymorphism

Polymorphism means the ability to take more than one form. An operation may exhibit different

behaviors in different instances. The behavior depends on the data types used in the operation.

Polymorphism is extensively used in implementing Inheritance using same name with either

Different number of Arguments or Different Data types of Arguments.

Types:- Compile Time (the compiler recognizes the binding between the function and its code

during compile time) and Run Time(the compiler recognizes the binding between the function and

its code during runtime)

8. Dynamic binding :-

1. Its also called Runtime Polymorphism, where the compiler recognizes the binding

between the function and its code during runtime.

2. Its implemented using Virtual Functions, during Inheritance.

9. Message Passing :-

1. It’s the process of passing Data between Objects of same Class and also of different

Classes.

Nonflying Bird Attributes: ………….. …………….

Flying Bird Attributes: ………… ………….

Parrot Attributes: ………….. …………..

Robin Attributes: ………… …………..

Panguin Attributes: ………… …………..

Kiwi Attributes: ………… …………..

Page 23: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

2. Its implemented using Function calling or by simply sharing data.

3. Types:- From User to Objects (done by invoking Function inside an Object) and From

Object to Object (by sharing Data of one Object with another Object).

4. Using Friend functions (with objects as input arguments), message passing can be done

between two or more Objects of Different Classes.

5. Using member Functions (with objects as input arguments), message passing can be done

between objects of same Class.

Structure of the C++ Program :

Simple C++ Program

// my first program in C++

#include <iostream>

void main ()

{

cout << "Hello World!";

}

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered

comments and do not have any effect on the behavior of the program. The programmer

can use them to include short explanations or observations within the source code itself. In

this case, the line is a brief description of what our program is.

C++ supports two ways to insert comments:

// line comment

Page 24: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

/* block comment */

#include <iostream>

Lines beginning with a pound sign (#) are directives for the preprocessor. They are not

regular code lines with expressions but indications for the compiler's preprocessor. In this

case the directive #include <iostream> tells the preprocessor to include the iostream

standard file. This specific file (iostream) includes the declarations of the basic standard

input-output library in C++, and it is included because its functionality is going to be used

later in the program.

void main ()

This line corresponds to the beginning of the definition of the main function. The main

function is the point by where all C++ programs start their execution, independently of its

location within the source code. It does not matter whether there are other functions with

other names defined before or after it.This function's definition will always be the first

ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.

cout << "Hello World";

This line is a C++ statement.This statement performs the only action that generates a visible effect in our first program.

cout represents the standard output stream in C++.The operator << is called the insertion

or put to operator and the meaning of the entire statement is to insert a sequence of

characters (in this case the Hello World sequence of characters) into the standard output

stream (which usually is the screen).

We could have written:

int main () { cout << "Hello World"; return 0; }

Notice that the statement ends with a semicolon character (;). This character is used to

mark the end of the statement and in fact it must be included at the end of all expression

statements in all C++ programs.

Compiling And Linking : Compiling and linking a C++ program depends on compiler and

operating system. Turbo C++ and Borland C++ provide an integrated program development

environment under MSDOS .They provide built in editor and a menu bar which includes options

such as File, Edit, compile and Run.

• First, the C++ preprocessor goes over the program text and carries out the instructions

specified by the preprocessor directives (e.g., #include). The result is a modified program

text which no longer contains any directives.

• Then, the C++ compiler translates the program code. The compiler may be a true C++

compiler which generates native (assembly or machine) code, or just a translator which

translates the code into C. In the latter case, the resulting C code is then passed through a

C compiler to produce native object code. In either case, the outcome may be incomplete

due to the program referring to library routines which are not defined as a part of the

program.

• Finally, the linker completes the object code by linking it with the object code of any

library modules that the program may have referred to. The final result is an executable

file.

Page 25: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

• Illustrates the above steps for both a C++ translator and a C++ native compiler. In practice

all these steps are usually invoked by a single command (e.g., CC) and the user will not

even see the intermediate files generated.

C++

Program

C

Code

Object

Code

Execut-

able

C++

COMPILER

NATIVE

C++

TRANSLATOR

LINKER

C

COMPILER

C++

Program

C++ I/O statement:

C++ I/O operations are called streams. There are two types of streams in c++ they are

1. Input streams 2. Output streams

Input streams: input streams are used to read data from input devices like keyboard, hard disc,

etc. by using a predefined input stream object “cin” and “>>” extraction operator to read data

from input devices.

Syntax: cin >> var; example: cin >> x ;

For example in the above statement the compiler wait for input data for variable x the input data is

then take from input device and then assigned to variable x. It is possible to read any type of data

using cin statement.The header file iostream.h must be included to use this statement in a

program.

Input cascading operation:

Input cascading means read values of more than one variable of different data types using single

input statement.

Syntax: cin >> var1 >> var2>> var3;

Example: cin >> x>>y>>z; //where x, y, z may be of different data type

Output streams: output streams are used to print data on output devices like monitor, discs etc.

by using a predefined output stream object “cout “ and “<<” insertion operator to read data from

output devices.

Syntax: cout << var; example: cout << x;

For example in the above statement the compiler prints value of variable x on output device. It is

possible to print any type of data using cout statement. The header file iostream.h must be

included to use this statement in a program.

Page 26: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Output cascading operation:

Output cascading means print values of more than one variable of different data types using single

output statement.

Syntax cout << var1 <<var2<<var3:

Example cout << x << y <<z; where x, y, z may be of different data type

Advantages of streams

1. Streams do not require explicit data types specification in I/O statement

2. Streams do not require explicit address operator prior to the variable in the input

statement

C++ Operators and Expressions

(i) Arithmetic Operators: (+, -, * , / , %)

(ii) Assignment Operators: (=, += , - = , *= , /=, %=)

(iii) Comparison and Logical Operators:

(a) Relational Operators (< , >, <= , >=)

(b) Equality Operator (==, !=(not equal to))

(c) Logical Operator (&& , || , ! )

(iv) Bitwise logical Operators:

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

>> Bitwise right shift

<< Bitwise left shift

~ Bitwise complement

(v) Special Operators

(a) Unary Operator

* contents of the storage field to which a pointer is pointing.

& Address of variable.

- Negative Value.

! Negation (0 , if value is not equal to 0, 1 , if value=0)

++ Increment

-- Decrement

//type Forced type of conversion

sizeof size of the subsequent data type or type in byte

(b) Ternary Operato. r (?:)

exp1 ? exp2 : exp3

Eg max= ( first > second) ? first : second;

(c) comma operator ( , )

(d) Scope operator ( : : )

The double colon : : operator is used as the scope resolution operator in

C++.A member function of the class is defined using the : : scooping

operator.

Eg. #include<iostrean.h>

#include<conio.h>

int a=10;

void main()

{ int a=5;

cout<<a; // 5

cout<<: :a; // 10

Page 27: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

}

#include<iostrean.h>

#include<conio.h>

class sample

{

public:

void input();

}

//return type of func classname: :memfunction

void sample : : input();

(e) new and delete operators: In traditional C the dynamic memory allocation

and deallocation are through library functions such as malloc, alloc, calloc

and free. C++ defines a new method for carrying out memory allocations

and deallocations i.e. using new and delete operators.

(f) Other operators

(a) Parenthesis for grouping expressions( () ).

(b) Membership operators ( [ ] , )

Type Conversion:

(a) cast operator.

(cast type) expression;

or

cast type (expression);

e.g a = (int) (19.2/4);

a = int (19.2/4);

Expressions: An expression is a collection of data objects and operands that can be evaluated

to a single value. An object is a constant , variable or any other expression.

e.g (5+6) * (5-8);

C++ control structures:

Control structures determine the direction or order in which statements within the block are

executed. Control

statements are used to design control structures. In CPP control statements can be classified as

1. Conditional control statements (if, if else, ladder if, switch .. case )

2. Iterative control statements ( for, while, do .. while)

3. Unconditional control statements (goto, continue, break)

(1) Conditional control statements:

Conditional control statements are used to control the flow of control based on condition

statement. For

example if , if else, switch etc.

If statement:

Syntax: 1. if (condition)

statement; // simple if statement

2. if (condition ) // if else statement

Statement

Page 28: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

else

Statement

3. else if (condition)

Statement

else if (condition)

Statement

else

Statement

The switch statement:

When there are a number of else alternatives as above, way of representing is by the switch

statement.

The general format of a switch statement is

Switch (expression)

{

case value1:

program statement

……

break;

case value2:

program statement

……

break;

case value’n’:

program statement

……

break;

default:

program statement

break;

}

(2) Iterative control statements

for loop:

for (variable = initial ; condition; amount of increment/decrement)

{

Lines to be repeated;

}

while loop:

initial condition

while (condition)

{ stmt;

stmt;

change of the initial condition;

}

do while loop:

{ stmt;

stmt;

}

while (condition);

Page 29: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

(3) Unconditional statements:

Unconditional statements are used to transfer the control from one place to other with out any

condition. They are generally used to branch or termination process. For example goto, break,

continue, and exit;

Syntax: goto – used to branch the control to a particular place

Break – to terminate the iterative statements

Continue – to get the next iterative value

Pointers in C++

A pointer is a variable which holds the address of any variable or a function. A pointer can refer

to an object of any one of the data type.

Pointer declaration:

Syntax : data type * variable_name; for example : int *x; or int* x; or int * x;

Pointer operator:

Pointer operator can be represented as * (asterik) with a variable name. For example if a variable

of integer data type and also declared * with another variable, it means the variable is of type

“pointer to integer”.

int *ptr ;

float *fptr;

char *cptr;

Address operator:

An address operator can be represented by the use of & (ampersand). The operator immediately

preceding a variable returns the address the of the variable.

E,g int a;

Int *p;

p = &a ; or int *p = &a; // address of variable a is assigned to pointer variable p.

& operator can be used only with a simple variable or an array element .

E.g &120 ; //invalid

int x[10];

&x; //illegal use of ampersand operator.

&x[0] or &x[i] //valid;

Constant pointer: C++ adds the concept of constant pointer and a pointer to a constant.

char * const ptr1=”GOOD”; // constant pointer

we can not modify the address that ptr1 is initialized to.

int const * ptr2 = &m; // pointer to a constant

ptr2 is declared as pointer to constant> It can point to any variable of correct type but the

contents of what

it points to cannot cannot be changed.

We can also declare both the pointer and the variable as constants in the following way:

Const char * const ptr = “xyz”;

This statement declares ptr as a constant pointer to the string which has been declared a

constant. In this case neither the address assigned to the pointer ptr nor the contents it points to

can be changed.

Page 30: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Void pointer:

Syntax: void *variable for example: void *x;

The void type of pointer is a special type of pointer; void pointers are pointers that point to a value

that has no type. This allows void pointers to point to any data type, from an integer value or a

float to a string of characters.

int .a;

char c;

void *p;

p = &a;

cout<<” Value of a=” , *((int *)p); //void pointer is typecasted to int type.

Null pointer:

A null pointer is a regular pointer of any pointer type which has a special value that indicates that

it is not pointing to any valid reference or memory address. This value is the result of type-casting

the integer value zero to any pointer type.

Syntax: data type * variable = NULL or data type *variable = 0

For example int *x = 0 or int *x = NULL:

Pointer Arithmetic:

ptr-- : Decrements the value by the size of the data type.

ptr++: Increments the value by the size of the data type.

--ptr : Decrements the value by the size of the data type before the statement is executed.

++ptr : Increments the value by the size of the data type before the statement is executed.

*ptr--: Retrieve the contents of location pointed by pointer then decrement the pointer.

*--ptr: Decrement the pointer then retrieve the contents of new location pointed by pointer.

*ptr++: Retrieve the contents of location pointed by pointer then increment the pointer.

*++ptr: Increment the pointer then retrieve the contents of new location pointed by pointer.

--(*ptr): Decrement the contents pointed by pointer by one then retrieve the new value.

(*ptr)--: First retrieve the content pointed by pointer , then decrement the content by one pointed

by

pointer.

++(*ptr): Increment the contents pointed by pointer by one then retrieve the new value.

(*ptr)++: First retrieve the content pointed by pointer , then increment the content by one

pointed by

pointer.

Reference Variable: C++ introduces a new kind of variable known as the reference variable. A

reference is an alias or an alternative name for an existing variable. All operations applied on

reference variables are also applied on original variable. The address of a reference variable is

same as the address of the original variable. Reference variable looks like ordinary variable and

behaves like pointer variable. A reference variable can be defined as:

Datatype &ref_varible = ori_varible;

Eg int a=5;

int &b = a;

cout<<a<<b; // output will be 5 5.

b= 20;

cout<<a<<b; // output will be 20 20.

Where b is a reference variable of a and a is a referent.

The following points can be noted about reference parameters.

A reference can never be null. It must always refer to a valid object or variable

Page 31: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Once a reference variable is created for one variable it cannot be reference variable for

another variable.

Reference never takes any extra space in memory.

Reference has to be initialized while declaring only.

Limitation: A variable(referent) can have more then one references but one reference variable can

have

only one referent.

Difference between Pointer variable and Reference variable.

Functions in C++ : A complex parts may be decomposed into a small or easily manageable parts

or modules called functions. Functions are very useful to read, write, debug and modify the

complex program. Functions are used to implement reusability of code .

The main Function: In C++ the main() function returns a value of type int to the operating system.

int main()

{

Pointer Variable Reference Variable

1. It is a special variable which can store

the address of another variable

It is a duplicate name (alias) given to any

variable.

2. Here the Pointer variable will be created

in the memory and then it can be

assigned any address.

No extra space is required. Only a duplicate

name is assigned to the same memory area.

3. Using * or de-referencing operator

along with the pointer variable the

value inside the address can be

accessed

By simply using an = or assignment

operator with the reference variable the value

can be changed

4. Used while implementing Call By

Address

Used while implementing Call By Reference

5. Common Syntax :-

Declaration :-

Data type *Pointer variable name ;

Acquiring address :-

Pointer variable = & variable name ;

Here the address of the ‘ variable ‘ would

be stored get stored in the ‘ pointer

variable ‘.

Manipulating data :-

*Pointer variable = value;

here the ‘ value ‘ would be assigned to

the ‘ variable name ‘.

Common Syntax :-

Declaration :-

Data type & reference = variable ;

Here the LHS ‘ reference ‘ name given would

become the duplicate name for the

‘ variable ‘ in the RHS

Manipulating data :-

reference = value ;

here the ‘ value ‘ would be assigned to the ‘

variable ‘, which would be reflected in both

the reference as well as the original

‘ variable’.

6. Example:-

int a = 10 ;

int *p ;

cout<< a ; // it would show 10

p = &a;

*p = 20;

cout<< a ; // it would show 20

Example :-

int a = 10;

int &b = a;

cout << a << b ; // It would show 10 10

b=20;

cout << a << b ; // It would show 20 20

Page 32: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

…………

…………….

return 0;

}

Steps of writing Functions :-

1. Function Prototyping :- Here we write the Function prototype, which represents the name of

function, number of input arguments and data-types of input arguments. The prototype describes

the function interface to the compiler.

Syntax :- return-data-type function-name ( input-argument-list along with their data-

types) ;

Example :- int add (int, int) ;

2. Function Definition :- Here we use along with the prototype, Opening and Closing curly

brackets, inside which we write the code of the function.

Syntax :- return-data-type function-name ( input-argument-list along with their data-

types) { …. }

Example :- int add (int a, int b) { return (a+b) ; }

3. Function Calling :- Here we use the function prototype, with out the return type and passing in

the real arguments. It causes the function to execute its code.

Syntax :- function-name ( argument-values) ;

Example :- add (10 , 20 ) ;

return statement: The keyword return is used to terminate the function and return a value to its

caller. The return statement may also be used to exit a function without returning a value. The

return statement may or may not include an expression.

Syntax:- return;

return (expression);

Categories of functions: A function depends on whether argument is present or not and whether

a value is returned or not.

Function with no argument and no return value.

void add ( void ); // function prototype

void main( )

{

add ( ); // function call.

}

void add (void) // function definition

{ int a=10 , b=20;

cout<<”addition is=”<<a+b;

}

Function with arguments but no return value. E.g void add ( int a , int b )

void add ( int , int ); // function prototype

void main( )

{ int a,b;

Page 33: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cout<<”enter value of a and b”;

cin>>a>>b;

add (a,b); // function call, a and b are actual arguments.

}

void add (int c, int d) // function definition , c and d are formal arguments.

{

cout<<”addition is=”<<c+d;

}

Function with arguments and a return value. E.g int add ( int a , int b ).

int add ( int , int ); // function prototype

void main( )

{ int a,b, sum;

cout<<”enter value of a and b”;

cin>>a>>b;

sum= add (a,b); // function call, a and b are actual arguments.

}

int add (int c, int d) // function definition , c and d are formal arguments.

{ int e;

e = c + d;

cout<<”addition is=”<<e;

return( e) ; //u can also pass expression like return( c+d)

}

Function with no argument but returns a value. E.g int add ( )

int number( void )

{ int m = number( );

cout<<”value is:” <<m;

getch();

}

int number(void)

{ int i;

cin>>i;

return(i);

}

Function that returns multiple values. //done by call by address.

Actual Arguments: An actual argument may be variable name , expression or constants

contained in a function call that replaces the formal parameter which is part of the function

declaration.

Formal Arguments: formal arguments are the parameters present in function definition which

may also be called as dummy arguments or the parametric variables . Formal arguments must be a

valid variable name. When function call is made only a copy of the values of the actual argument

is passed to the called function. Any changes in formal argument does not effect the actual

argument.

Parameter passing mechanisms in C++:-

The parameters can be passed in 3 ways in C++. They are

1) Call by value 2) Call by address 3) Call by reference

Page 34: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Call by value: -

In C++ by default a function call passes parameters by value

In this mechanism the values of actual parameters will be passed to a separate set of

variables known as formal parameters

The formal parameters of type value parameters

Any changes made to formal parameters will not affect the corresponding actual

parameters.

Only one value to be return from function

e.g void main ()

{ void swap (int, int); // function prototype

int a=10,b=50;

swap(a,b); // function call as call by value

cout<<a<<b; // 10 50

}

void swap (int x, int y) // function definition.

{ int t; t=x; x=y; y=t;

cout<<x<<y; // output 50 10

}

Call by address:-

In C++ it is possible to call a function by passing address this technique is known as call by

address.

In call by address technique the formal parameters must be a pointer type and they

receive the addresses of actual parameters.

Any changes to the formal parameters are automatically reflected back to the actual

parameters in the main program.

It is possible to make a function to return more than one value to the calling program

The address can be generated by using address operator &.

e.g void main ( )

{ void swap (int * , int * ); // prototype

int a,b;

a=50; b=30;

swap(&a,&b); /*call by address*/

cout <<a<<b<<endl;

}

void swap (int *p1, int *p2) / *Receiving the addresses in pointers*/

{ int t; t=*p1; *p2= *p1; *p2=t; }

From the above example, it is clear that the main() function can display the swapped values of a

and b.

Call by Reference:-

The formal parameters must be of type reference

When we pass parameters by reference the formal parameters becomes like an alias

variable to the formal parameters

To pass arguments by reference, the function call is similar to that of call by value.

Ex swap(a,b)

In the function decelerator the formal parameters are preceded by the ‘&’ operator.

Page 35: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

It is possible to return more than one value from a function to the main program

Any changes to the formal parameters are automatically reflected back to the actual

parameters in the main program.

Using this method no duplicate set of variables are crated.

Hence the complete program of swapping 2numbers using call by reference can be shown as

follows.

void main ( )

{ void swap (int &x, int & y);

int a,b;

a=50; b=30;

swap(a,b); // function calling.

cout<<a<<b<<endl; }

void swap(int &x, int &y)

{ int t; t=x; x=y; y=t; }

Example: Square of two numbers using call by value, call by address and call by reference.

(i) call bye value:

void main( )

{ void square ( int , int ); // function prototype

int a,b;

cout<<”enter value of a and b”;

cin>>a>>b;

square(a,b); // function call, a and b are actual arguments.

}

void squre (int c, int d) // function definition , c and d are formal arguments.

{

cout<<”square is=”<<c*c<<d*d;

}

(ii) call bye address:

void main( )

{ void square ( int *, int *); // function prototype

int a,b;

cout<<”enter value of a and b”;

cin>>a>>b;

square(&a, &b); // function call, a and b are actual arguments.

cout<<a<<b // square values

}

void squre (int *p1, int *p2)

{

*p1=(*p1) * (*p1) ; *p2=(*p2) * (*p2) ; }

(iii) call by reference:

void main( )

{ void square ( int & , int &); // function prototype

int a,b;

cout<<”enter value of a and b”;

cin>>a>>b;

square(a, b); // function call, a and b are actual arguments.

cout<<a<<b // square values

}

void squre (int &x, int &y) // function definition , x and y are reference variable.

Page 36: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

x= x*x ; y=y*y ; }

There are Three categories of Calling Functions in C++

1. Return by Value :-

1. Here the value returned by the function after it is executed is a simple value.

2. Example :-

int greater(int a, int b)

{

if ( a > b)

{ return a ; }

else

{ return b ; }

}

main()

{

int i, j ;

cin >> i >> j ;

cout << ” Greater Value is:- “ << greater ( i , j );

}

2. Return by Address : -

1. Here the returned value is an address, and has to be received in a pointer.

2. Example :-

int* fill (int *p)

{

p = new int [5] ;

for ( int j = 0 ; j < 5 ; j ++ )

{

cin >> p [ j ] ; }

return p ;

}

main()

{

int *q;

q = fill ( q ) ;

for ( int k = 0 ; k < 5 ; k ++ )

cout<< q [ k ] ;

}

3. Return by Reference :-

1. Here value returned is the reference to a variable.

2. Example :-

int& greater(int & r, int & j)

{

if ( r > j )

{ return r ; }

else

{ return j ; }

}

main()

{

int a = 10, b = 5 ;

greater ( a , b ) = 100 ; // Here the reference to the greatest of a and b will

be returned

and will be assigned the value 100

Page 37: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cout<< a << b ; // output 100 5

}

Inline functions: -

Function execution involves the overhead of jumping to and from the calling statement. Trading

of this overhead in execution time is considerably large whenever a function is small. Hence in

such case inline functions are used. Inline functions are those whose function body is inserted in

place of the function call statement during the compilations process. An inline function definition

is similar to an ordinary function, except that the keyword inline precedes the function definition.

By default every function created in C++ is Inline.

The syntax for defining an inline function is as follows:

inline function- header ( )

{ Body of the function;

}

eg. inline float getdata (int a, float b)

{ return (a+b); }

void main ()

{ int a= 35; float b= 18.5;

cout <<“The sum is “<<getdata (a,b); }

The inline functions are similar to macros in ‘c’ language. But the major drawback with macros is

that the error checking does not occur during compilation.

The following are the situations where inline functions may not work properly

1. Functions returning values, having a loop, a switch or a go to exists

2. If the function contains static variables.

3. If inline functions are recursive.

Disadvantages: -

1. In line functions may require more memory in the program as they are basically

expanded while compiling the program.

2. The speed benefits of inline functions diminish as the functions grows in size.

The inline key word sends a request but not a command to the compiler. Hence the compiler can

ignore the request if the function definition is too long.

Default arguments: -

In c++ default arguments are used to call a function without specifying all of its arguments. In the

function prototype declaration the default values are given. Whenever a call is made to a function

without specifying an arguments, the complier will automatically assign values to the parameters

from the default function prototype declaration. A default argument can in the function prototype.

Once it is defined, it cannot be redefined at function definition argument list .

Some points regarding default arguments;

1) A default argument is checked at the time of declaration and evaluated at the time of call.

2) Default argument is used only when any argument value is missing at function call.

3) We must add the default parameters from right to left.

4) We cannot provide a default parameter in the middle of an argument list

5) Default arguments are useful where some arguments always have the same value

For example: float amount (float principle, int period, float rate = 0.15);

Note: - principle, period are general formal parameters, rate is Default argument.

For ex: the function call

Value= amount (5000, 7); // one argument missing hence default value will be taken.

The above function call passes

Page 38: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

5000 principle

7 periods

Then the function use the default value for rate parameter as 0.15 rates.

e.g. void sum( int , int x=10, int y=20); // function prototype with default argument list.

void main()

{ int a=5,b=15,c=5;

sum(b); // if we call the function like sum(a,b,c) then there is no use of default

arguments.

-------------

}

void sum( int a1, int a2, int a3) //function declaration

{ int temp;

temp = a1+ a2+a3; // a2=10 a3=20 by default arguments. I.e temp=45

}

Const arguments :-

1) Here we declare the arguments as constants by using “ const “ keyword, in the function

definition.

2) The arguments declared as const cannot be changed in side the function definition.

3) During calling of the function the const arguments would acquire the values initially given in

the call.

4) Syntax :- return-type function-name ( const argument, …. ) { function definition code }

5) Example :-

main( )

{ void get(int, const int);

add( 5 , 5 ) ;

getch(); }

void add ( int a , const int b )

{

a=10; // can be reinitialized because it is a simple variable.

b=20 ; // Not allowed as its declared const

cout << ( a + b ) ; // output 15

}

Function overloading:-

Function overloading can be defined as define a set of functions having same name and different

signatures. The same function name will be used with different number of parameters and

parameters of different type. We can use the same function name to create function that performs

a variety of different tasks. This is known as function overloading (function polymorphism) in

OOP. The function can perform different operations depending on the argument list in the

function call. At the time of calling correct function to be invoked is determinates by checking the

number and type of the argument but not on the function return type.

For ex an overloaded add( ) function handles different types of data as follows.

void max (int a, float b); // prototype 1

void max(int a, int b, int c); // prototype 2

void max (double x, double y);// prototype 3

void max(float p, int q); // prototype 4

The following function calls can be given in the program

x= add (0.75,5);//uses prototype 4

Page 39: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

y= add (5,10,15);// uses prototype 2

z= add (5,10.5);//uses prototype 1

p= add (12.5,17.5); // uses prototype 3

Rules that govern the usage of function over loading:

1. The compiler first tries to find an exact match, in which the type of actual parameters are

the same and use that function.

2. If an exact match is not found then the compiler converts the arguments as follows.

i. char to int

ii. float to double

iii. int to float or double

iv. All these conversions take place to find a match.

3. Some times compiler generate ambiguity errors because the compiler may not be able to

decide what signature function should be called. If the conversion is possible to have

multiple matches then the compiler generates an error message. Suppose we use the

following 2 functions.

long square (long n);

double square (double x);

A function call such as square (100) will cause an error because ‘int’ argument 100 can be

converted to either long or double. The following is an ex: program that shows the usage of

function overloading

#include <iostream.h>

#include <iomanip.h>

void main()

{ float area (int r); // over loaded function

int area (int l, int b); //over loaded function.

float a;

int a1,l,b,r , a1 ;

cout <<“enter the radius of the circle “<<endl;

cin>>r;

a=area(r);

cout << “ area of the circle is “<<a<,endl;

cout <<“enter the length and breadth of the rectangle”;

cin>>l>> b;

a1= area(l,b);

cout<<“area of the rectangle is “<<a1<endl;

float area (int r)

{ return (3.141*r*r); }

int area (int l, int b)

{ return (l*b);

}

Page 40: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Classes And Objects

Structure Class

Structure can be defined as a collection

of dissimilar data items.

Class can be defined as combination

of data items and functionality applied

on that data

By default all members are public By default all members are private

The size of the structure = size of the

individual data items of a structure

The size of the structure = size of the

individual data items of a class

Separate copy of data members are

created for all structure variables

Separate copy of data members and

only one copy of member functions

are created for class

To create a structure variable use

keyword struct

To create a class variable the keyword

class is optional

It is Not possible to inherit structures It is possible to inherit class

Structure are called as Passive data

item

Classes are called as Active data items

Class: Class can be defined as combination of data members and member functions applied on

that data. It allows the data to be hidden from the external use. A class can also be called as an

abstract data type (ADT).

Abstract Data Type can be defined as the technique of creating new data types whose

implementation details are hidden and can only be handled using the publicly accessible member

function

It’s a User Defined Data-type.

1.The Data declared in a Class are called Data-Members of the Class.

2.The Functions declared or defined in a Class are called Member-Functions of the Class.

The members of a Class can only be accessed through Objects of the class.

Syntax: class class_name

{

access specifier:

member1;

access specifier:

member function;

...

} [object_name];

for example

class a

{ private;

int x

public :

void show() {cout << a;}

};

Where class_name is the name for a class (user defined type) and the optional field object_name

is one, or several, valid object identifiers. The body of the declaration can contain members,

which can be either data members or member functions.

The following are the characteristics of a class

The keyword class specifies abstract data type of type class name.

The body of a class is enclosed with in braces and terminated by a semicolon

The functions and variables with in the class are collectively called as members

The members that have been declared as private can be accessed only from with in the class.

Class definition is only a template and does not create any memory space for a class

By default all the members are of type private .

Page 41: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Three Access Specifiers :-

Public :-

Any member declared under this specifier is Accessible from Outside the

class, by using

the object of the Class.

The Public members of a Class get Inherited completely to the Child

Classes.

The keyword “ public : “ is used.

Syntax :-

Class definition

{ public :

declarations or definitions

} ;

Example :-

class A

{ public :

int a;

} ;

main()

{ A oba ;

oba . a = 10 ; // we have set the value of variable ‘ a ‘ in

object ‘ oba ‘ to 10

}

Private :-

Any member declared under this specifier is Not Accessible from Outside

the Class.

The Private members are accessible to only the Member Functions and

Friend Functions

in the Class.

The Private members of a Class Never get Inherited to the Child Classes.

The keyword “ private : “ is used.

Syntax :-

Class definition

{ private :

declarations or definitions

} ;

Example :-

class A

{ private :

int a;

public :

void fill ( )

{ cin >> a ;

}

} ;

main()

{

A oba ;

// oba . a = 10 ; // invalid as ‘ a ‘ is private member.

oba . fill ( ) ; // valid as fill ( ) is a public member.

}

Protected :-

Page 42: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Any member declared under this specifier is Not Accessible from Outside

the class, by using the object of the Class.

The Protected members of a Class get Inherited completely to the Child

Classes and they maintain their Protected visibility in the child Class.

The Protected members are accessible to only the Member Functions and

Friend Functions in the Class.

The keyword “ protected : “ is used.

Syntax :-

Class definition

{ protected :

declarations or definitions

} ;

Example :-

class A

{ protected :

int a;

public :

void fill ( )

{ cin >> a ;

}

} ;

main()

{ A oba ;

// oba . a = 10 ; // invalid as ‘ a ‘ is protected member.

oba . fill ( ) ; // valid as fill ( ) is a public member.

}

Member function defined outside the class definition:

1. To declare the member function of a class outside the class definition the function

prototype declared within the body of a class and defined them out side the body of a

class.

2. Member ship identity label (class_name :: ) differentiate member functions and non

member function in a program.

3. By default the member function defined outside the class definition is non-inline.

4. To make it inline by explicitly adding inline as prefix to the member function in the

definition.

syntax

class classname

{ access specifier:

return data type functionname(arguments);

//declaration

};

return data type classname ::

functionname(argument) // function definition

{ function body;

}

for example:

class a

{ public;

void show(); // prototype

};

void a:: show()

{ cout << “this is outside the class “ ; }

Here the membership label class_name:: tells the compiler that the function is the member of the

specified class. The scope of the function is restricted to only the objects and other members of

the class.

Page 43: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

To make the member function defined out side the class as an inline by adding inline as a prefix to

the member function.

Syntax Return data type inline class_name :: function name(arguments)

{ function body ; }

The following are the properties of a member function.

Several different classes can use the same function name; the membership label will

resolve their scope

A class can have multiple member functions with the same name as long as they differ in

terms of argument specification (data type or number of arguments)

Member functions can access the private data of the class, but a non-member function

cannot.

A member function can call another member function directly, without using a dot

operator.

There is no need to used member of operator (.) to access data members or member

function of a class within the class definition.

Objects:

Object can be defined as an Instance of a class. The process of creating objects (variables) of the

class is called class instantiation. In C++ the class variables are called as objects. The complier

allocates required memory for objects. The size of an object is equal to the sum of the sizes of the

individual data items of a class. The following is the general syntax of declaring objects.

Type1: class class_name ob1,ob2,ob3........obn;

Type2: class_name obj1.obj2,obj3,…objn;

Where class_name is the name of the class for which we want to create objects.

ob1, ob2,.... obn are the objects of class name.

Accessing class members:-

To access members of a class using the member off operator dot ( . )

It is not possible to access private data members of a class out side the class definition using dot

operator

The member access operator is not required to access data members within the class definition.

Syntax for accessing members of a class:

Access data members: object_name.datamember;

For Pointer Objects : Pointer-Object-Name -> member-name ;

Access member functions: object_name.memberfunction(actual_parameters);

The following is an example of creating an object of type ’item’ and invoking its member

function.

void main ( )

{ item x; // creating an object of type item

x. getdata (20,20.5);

x put data ( );

}

Memory allocation for objects:-

For each object of a class a separate copy of data members and one copy of member functions is

created. For each object a separate memory is allocated and the address of that memory is stored

in this pointer. By using this pointer the unique copy of member function of all the objects of a

class are identified. This pointer is passed automatically to all the member functions of a class.

Page 44: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Exapmle:

#include<iostream.h>

#include<conio.h>

class sample

{ public:

int a ;

void get()

{ cout<<"\nenter any no:";

cin>>a; }

void show()

{ cout<<"\n value of a="<<a; }

};

//sample a1,a2;

class try

{ public:

int b;

void show()

{ cout<<"enter value of b:";

cin>>b;

cout<<"value of b is"<<b;

a1.a=202; // undefined symbol a1

a1.show(); //undefined symbol a1

}

};

try i1;

void main()

{ sample a1;// if we create object of class here then we can not access its members in class try.

clrscr();

i1.show();

a1.get();

a1.show();

getch();

}

Exapmle 2:

void main()

{

clrscr();

class sample

{ private:

int a ;

void show()

Page 45: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{ cout<<"\n**value of a="<<a;

cin>>a; }

};

sample a1,a2;

a1.show(); //error ,although the calss is define inside the main() but its members are private

,so cannot

getch(); accessible outside of the class.

}

Global class: A class is said to be global class if its definition occurs outside the bodies of all

functions in a program.

class sample

{ public:

int a ;

void get()

{ cout<<"\nenter any no:";

cin>>a; }

void show()

{ cout<<"\n value of a="<<a; }

}; sample s1 ; // global object

void main()

{ sample s2 ; //local object of a global class

s1.get();

s1.get(); s2.get(); }

Local Class: A class is said to be local class if its definition occurs inside the functional body.

void main()

{ class sample //local class

{ private:

int a ;

void show()

{ cout<<"\n**value of a="<<a;

cin>>a; }

};

sample a1,a2; // local objects

a1.show(); //error ,although the calss is define inside the main() but its members are

private ,so cannot

getch(); accessible outside of the class.

}

NOTE: A global object can only be declared using a global class type, while local objects can be

created from both class type i.e global as well as local.

Nested Class :-

1. Nested Classes are the Classes defined inside a Class.

2. A class is defined within another class is called a nested class.

3. The Outer class is known as enclosing class.

4. Member function of a nested class have no special access to members of an enclosing class.

5. Member function of an enclosing class have no special access to members of a nested class.

6. Object of inner class can be created by using : : operator.

Page 46: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Outer_class: : inner_class obj1;

7. The member function of the nested(inner ) class can be defined outside its scope.

Return_type of fun outer_class: : inner_class: : fun() { }

#include<iostream.h>

#include<conio.h>

class sample

{ public: int a;

class inner

{ public:

int b;

void get_in()

{ cout<<"enter valueof b:"; cin>>b; }

}i2;

void show_out()

{ i2.b=100;

cout<<"\n**value of a=";

cin>>a;

cout<<"value of b="<<i2.b; }

};

sample a1;

sample: :inner i1;

void main()

{ clrscr();

a1.show_out();

i1.get_in();

i2.get_in(); //undefined symbol i2

getch();

}

Note: if we declare the inner class under private access specifier.

class sample

{ private: int a;

class inner

{ public: int b;

void get_in()

{ }

}i2;

public: void show_out()

{ }

};

although its define under private access specifier ,but its members are public.its members wont be

accessible when we declare them under private access specifer.

e.g class inner { private: int b; void get_in() { } }i2;

Example of nested class:

#include<iostream.h>

#include<conio.h>

class sample

{ private: int a;

class inner

{ public:

int b,c;

void get_in()

{ cout<<"enter value of b,c";

cin>>b>>c; }

Page 47: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

void show_in()

{ cout<<"b="<<b<<"c="<<c; }

};

public:

void get1()

{ cout<<"enter a";

cin>>a; }

void show1()

{ cout<<"a="<<a;

inner i1;

i1.get_in();

i1.show_in(); }

};

sample a1;

void main()

{ clrscr();

a1.get1();

a1.show1();

getch();

}

Static data members :-

1. Only a single copy of the Static data members are shared between Objects of the Class.

2. Static data members are initialized using the data type Class-Name and Scope-Resolution

Operator and data member-Name

3. The Static members are declared using “ static “ keyword.

4. The access rule of the data members of a class is same for the static data member also.

5. The Static Data Members should be created and initialized before the main function control

block

begins.

6. Syntax :-

For variables :- static data-type variable-name ;

#include <iostream.h>

#include<conio.h>

class sample

{

static int a; // declaration

public:

void incr( )

{ a=a+1; }

void putdata ( )

{ cout <<"a="<<a<<endl; }

};

int sample::a; //by default initialize with 0

void main ( )

{ sample x,y,z;

y. incr ();

z.putdata( );

}

Example: #include<iostream.h>

#include<conio.h>

Page 48: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

int g=10;

class sample

{

int a;

public :

static int b;

void show()

{

b++;

cout<<"\nb = "<<b;

}

}s1,s2;

int sample :: b;

class other

{ int c;

public:void value()

{ s1.b+=2;

cout<<"\n--b--="<<s1.b;

}

} o1,o2;

void main()

{ clrscr();

s1.show() ;

o1.value();

s2.show();

o1.value();

getch();

}

output:

b=1;

--b--=3

b=4

--b--=6

Static member function:-

Like static member variables we can also have static member functions. A member function that

is declared as static has the following properties.

1. A static member function can have access to only other static members(functions or

variable) declared

in the same class.

2. A static member function can be called using the class name a follows.

a) Class_name : : function_name ( )

3. A static member function also calls the class constructor explicitly.

4.

The differences between a static member function and non-static member functions are as

follows.

A static member function can access only static member(data and member functions)

data and functions outside the class. A non-static member function can access all of the

above including the static data member.

A static member function can be called, even when a class is not instantiated, a non-

static member function can be called only after instantiating the class as an object.

s1 s2 void show()

a a

b

Page 49: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

A static member function cannot be declared virtual, whereas a non-static member

functions can be declared as virtual

A static member function cannot have access to the 'this' pointer of the class.

A static or non static member function cannot have the same name.

#include<iostream.h>

#include<conio.h>

class test

{

int code;

static int count ;

public:

void setcode( )

{ code =++ count; }

void showcode ( )

{cout<<"object_number"<< code<<endl ; }

static void showcount ( ) // static member function.

{ cout <<" count" <<count<<" \n";

cout<<”code =”<<code //error , code is a non static member

function.

}

};

int test :: count;

void main ( )

{

test t1,t2,t3;

t1. setcode ();

t2. setcode ();

test :: showcount ( );

t3. setcode ( );

test:: showcount ( );

t1. showcode ( );

t2. showcode ( );

t3. showcode ( );

}

Output: -

count : 2 count : 3

object number :1object number : 2 object number : 3

Code code code t1 t2 t3

count setcode()

showcode() showcount()

1 2 3

3

Page 50: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Friend Functions :-

1. Friend functions are Not member functions of any class, but they can access the private,

protected and public members of the class.

2. They are declared using “ friend “ keyword.

3. They Don’t belong to any specific Class.

4. They can be invoked as ordinary functions, with out using any object.

5. They can be defined outside the Class, here also they are defined like ordinary functions and

Not like member functions.

7. The access specifiers does not effect the visibility of Friend Functions.

8. Usually a friend function receives the object as arguments.

9. Syntax :-

friend return-type function-name ( input-arguments ) ;

10. member function of one class can be defined as friend function of another class.In such case

they are

defined using scope resolution operator as shown below.

class X

{ ………

int fun1(); //member fun of X

};

class Y

{ ………..

…………

friend int X: :fun1();

};

Example:

#include<iostream.h>

#include<conio.h>

class sample

{ int a,b;

public:

void get()

{ cin>>a>>b; }

void show()

{ cout<<a<<b; }

friend void swap(sample s);

};

void swap( sample s1)

{ int temp=s1.a;

s1.a =s1.b;

s1.b = temp;

cout<<”a=”<<s1.a<<”b=”<<s1.b;

}

void main()

{ clrscr();

sample s2;

Page 51: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

s2.get();

cout<<” before swapping:”<<endl;

s2.show();

cout<<”After swapping:”

swap(s2); //function call swap(s2) passes the object s2 by value to the friend function.

getch();

}

Note: Actual swapping can be done by reference or address, we can make friend void swap(

sample &); or swap( sample *);

Example 2: swapping the data members of two classes using friend function.

#include<iostream.h>

#include<conio.h>

class second; // Forward declaration to satisfy the compiler about class B

class first

{ int a ;

void get()

{ cout<<"enter the value of a:";

cin>>a;

}

friend void swap ( first &,second &) ;

};

class second

{

int b ;

void get()

{ cout<<"enter the value of b:";

cin>>b;

}

friend void swap ( first &,second &);

};

void swap ( first &ob1,second &ob2 )

{ ob1.get();

ob2.get();

int temp;

temp = ob1.a ;

ob1.a = ob2.b ;

ob2.b = temp ;

cout<<"a="<<ob1.a<<"\nb="<<ob2.b;

}

void main()

{

clrscr();

first ob1;

second ob2;

swap(ob1,ob2) ;

getch();

}

Example 3: Finding greatest between data member of one class and another class by making

the member function of one class as a friend function of another class.

Page 52: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

#include<iostream.h>

#include<conio.h>

class second; // Forward declaration to satisfy the compiler about class B

class first

{ int a ;

void get()

{ cout<<"enter the value of a:";

cin>>a;

}

public: void greatest(second);

};

class second

{

int b ;

void get()

{ cout<<"enter the value of b:";

cin>>b;

}

friend void first:: greatest(second);

};

void first::greatest (second ob2 )

{ get();

ob2.get();

if(a>ob2.b)

cout<<"greatest is"<<a ;

else

cout<<"greatest is:"<<ob2.b;

}

void main()

{

clrscr();

first ob1;

second ob2;

ob1.greatest(ob2) ;

getch();

}

Friend classes :

We can also declare all the member function of a class as friend function of another class using

“friend class”.

Eg

class first

{ ……………

friend class second;

};

class second

{ ……….

……….

}

Page 53: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Constructor: 1. It’s a special function which has the same name as that of the Class name.

2 It has No Return-Type, not even void

3 It should have public or protected access within the class and rarely declared as private.

4 Constructor overloading is possible.

5 Constructors cannot be virtual.

6 It can not be static.

4. Default arguments are possible.

5. They are invoked automatically as soon as Objects of Class are created.

7 We can explicitly call Constructors of a Class.

8 it is possible to have more than one constructor in a class.

7. They can Not be Inherited.

Page 54: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

9. There are Three Basic Categories of Constructors.

a. Default Constructor: It takes no parameters and performs no processing other than

reservation of memory. It will always call by the compiler, if no user defined

constructor is being provided.

Syntax :- class-name ( ) { code } ;

b. Parameterized Constructor

Syntax :- Syntax :- class-name ( parameter-list ) { code } ;

c. Copy Constructor.

Syntax :- class-name ( reference of the same class) { code } ;

10. If in any Class the Default Constructor is not defined then the compiler calls the implicit

Default Constructor for Initializing objects of the Class. If there exists a Default Constructor

defined in the Class then the defined Constructor will be called.

11. If any of the three categories of Constructors are defined in the Class then the compiler in any

case would never use the implicitly created Constructor, it would only use the user defined

Constructor.

Default constructor:

class sample

{ int a, b;

public:

sample()

{ a=0;b=0;

}

void show()

{ cout<<a<<b;

}

};

void main()

{ sample s;

s.show();

}

Destructors :-

1. It’s a special function which has the same name as that of the Class name.

2. It has No Input-Arguments and No Return-Type, not even void.

3. Its definition is preceded by Tild symbol “ ~ “.

4. Its called implicitly as soon as the scope for any object finishes. Its invoked for every object .

5. The compiler creates a Destructor for every Class implicitly by default.

6. If a Destructor is explicitly defined then the compiler will always use the explicitly defined

Destructor.

7. Its generally used to free up the spaces allocated by using “ new “ operator during calling of

Constructors. The de-allocation should be done using “ delete “ operator

8. The object that is created First is Destructed Last and object created Last is Destructed First.

9. Syntax :- ~class-name ( ) { code }

9 Example :-

Write a program to count the number of Objects created and destroyed using constructor and

destructor functions. The objects should be identified by a unique ID, which should be

mentioned while creation and destruction of the object.

class sample

{

static int count;

int a;

public:

sample() //Constructor

Page 55: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

a=++count

cout<<"\n"<<" Object number = "<<a<<” is created”;

}

~sample() //Destructor

{

cout<<"\nObject number = "<<a<<”is destroyed”;

}

};

int sample::count;

void main()

{ clrscr();

{

sample ob1; //Created First Destructed Last

sample ob2; //Created Second Destructed Last Second

sample ob3; //Created Last Destructed First

} //As scope is finishing so Destructors would be called

getch();

}

Overloaded constructors (or) multiple constructors in a class :

It is possible to have more than one constructor function with in the same class by varying the

argument list. This concept allows overloading the constructor function. The following is an

example

class sample

{ int m,n;

public: sample ( ) // constructor -1

{ m=n=0; }

sample (int i)// constructor - 2

{ m=n=i; }

sample (int x, int y) // constructor - 3

{ m=x; n=y: }

};

Thus the following declaration statements causes the appropriate constructors

sample i; // calls constructor-1

sample i(10); //calls constructor-2

sample i(10,20); // calls constructor -3

Constructors with default arguments:-

It is possible to define constructors with default arguments. For ex. The constructor ‘complex’

can be defined as follows

complex (float real, float imag=0);

The default value of the argument imag is zero

Then the following statements, complex C(5.0); Assigns the value 5.0 to the real variable and 0.0

to imag by default however the statement/ complex C(2.0,3.0); assigns 2.0 to real and 3.0 to imag.

Here the actual parameter 3.0 overrides the default value (0.0)

Copy constructor:- A copy constructor is a special constructor in the C++ programming

language used to create a new object as a copy of an existing object. This constructor takes a

single argument: a reference to the object to be copied.

Page 56: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Normally the compiler automatically creates a copy constructor for each class (known as an

implicit copy constructor) but for special cases the programmer creates the copy constructor,

known as an explicit copy constructor. In such cases, the compiler doesn't create one

There are four instances when a copy constructor is called:

1. When an object is returned by value

2. When an object is passed (into a function) by value as an argument

3. When an object is constructed based on other object (pf same class)

4. When compiler generates a temporary object (as in 1 and 2 above; as in explicit casting,

etc...)

Constructors of a class can be invoked by using existing objects of the class.

Syntax :- obect . class-name :: constructor-function-call ;

#include <iostream.h>

#include<conio.h>

class code

{ int d;

public:

code()

{cout<<"\ndefault constructor";

} // default constructor

code(int a) //constructor -2

{ d=a;

cout<<"\nparameterized contrctr";

}

code(code &x)//copy constructor

{ d=x.d;

cout<<"\ncopy cntrctr";

}

void display( )

{ cout<<"\nd="<<d<<endl;

}

};

void main( )

{ clrscr();

code A(100); //calls constructor - 2

code B(A); //calls copy constructor

code C=A; //calls copy constructor

code D; //calls no argument constructor

D=A;// It is assignment not initialization hence no copy const. will be called

A.display ( );

B.display ( );

C.display ( );

D.display ( ) ;

getch();

}

Operator Overloading :-

Page 57: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

1 It’s a type of Polymorphism, where we can give additional meaning or implementation to

existing operators.

2. But the usage of Overloaded Operators should follow the usual rules laid down by the

compiler.

3. Operator overloading is accomplished by means of special kind of function. Operator

overloading can be carried out by means of either member function or friend function.

Syntax: return_type operator operator t o be overloaded( parameters);

Eg: void operator ++( ) // same as void increment();

/*4. When using Type-Casting operators the following points need to be remembered :-

a. It can Not be declared as Friend, so it has to be a member function.

b. No return-type not even void.

c. No input-arguments not even void. */

Rules for overloading operators:-

Only those operators that are predefined in the c++ compiler can be overloaded. New

operators cannot be created such as ( $ ,# , @).

Overloaded operator can not take default arguments.

We can’t change the basic meaning of an operator, i.e., we can’t redefine the + to

subtract one value from the other value.

We cannot overload any preprocessor symbol such as #.

We can not change the precedence or grouping of an operator nor we can change the

no of arguments it expects.

Unary operators overloaded by means of a member function take no arguments and

return no values. But unary operators overloaded by means of a friend functions take

one reference argument.

Binary operators overloaded through a member functions take one argument and those,

which are over loaded through a friend function, take 2 arguments.

Overloaded operators follow the syntax rules of the original operators. They can’t be

overridden

Binary arithmetic operators such as +, -, *, / must explicitly return a value.

There are some operators that can’t be overloaded (::, *, . , ?:, sizeof().

Using friend functions to overload >> and << operators

The following is an example program of overloading relational operator == to compare the 2

given complex No’s.

OPERATOR MEANING

Sizeof ( ) size of operator

. Membership operator

.* Pointer to member operator

:: scope resolution operator

?: Ternary (or)conditional operator

it is possible to overload operators by using special member function “operator “ or a friend

function calling operator member function.

The general form of overloaded operator member function is as follows

return type class name : : operator op(argument list)

The assignment operator has some additional restriction. It can be overloaded as a non-static

member function, not as friend function. It is the only operator that can not be inherited. A derive

class can not use a base class assignment operator.

Operators that cannot be overloaded as friend.

Page 58: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

= operator(assignment operator)

( ) operator (function call operator)

[ ] operator (subscript operator)

operator (arrow operator)

Ex: class sample

{ int x;

sample()

{ x=10; }

void operator +(int I )

void add( int I)

{ x=x+I;

}

void show( )

{ cout<<x;

}

void main()

{

sample obj;

obj.add(20) //obj+10;

obj.show();

getch();

}

output: 30.

Generate fibonacci series by overloading

(i) prefix increment operator

(ii) postfix increment operator

1)SOURCE CODE ::

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<string.h>

class fib

{

int a,b,c;

public:

fib()

{

a=0;

b=1;

c=a+b;

}

void operator ++()

{

cout<<"\n\n"<<c;

a=b;

b=c;

c=a+b;

}

};

Page 59: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

void main()

{

clrscr();

fib obj,obj1;

int i,n;

cout<<"\n\n Enter the no. of term's upto which series is to be displayed : ";

cin>>n;

cout<<0<<"\n\n"<<1;

for(i=0;i<n-2;i++)

{ ++obj;

}

getch();

}

Write an OOP program to overload = = operator to compare two strings.

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<string.h>

class string

{

char s1[20];

public:

void get()

{ cout<<"\n\n Enter any string : ";

gets(s1);

}

int operator ==(string x)

{

int comp;

comp=strcmp(s1,x.s1);

if(comp==0)

return(1);

else

return(0);

}

};

void main()

{

string obj,obj1;

clrscr();

obj.get();

obj1.get();

if(obj==obj1)

{

cout<<"\n\n String's are equal ";

}

else

{

cout<<"\n\n String's are unequal ";

}

getch();

}

Page 60: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Overload the binary operator + using friend function to add two objects.

#include<conio.h>

#include<iostream.h>

class fib

{ int c;

public:

void get()

{ cin>>c;

}

friend fib operator +(fib &,fib &);

void show()

{ cout<<"\nc="<<c;

}

};

fib operator +(fib &x,fib &y)

{ fib z ;

z.c=x.c+y.c;

return(z);

}

void main()

{

clrscr();

fib f1,f2,f3;

f1.get();

f2.get();

f3=f1+f2;

f1.show();

f2.show();

f3.show();

getch();

}

Write an OOP program to overload = operator to copy the contents of one string object to another

string object.

SOURCE CODE ::

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<string.h>

class string

{

char s1[20];

public:

void get()

{

cout<<"\n\n Enter any string : ";

gets(s1);

}

void show()

Page 61: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

cout<<"\n\n The copied String is : ";

puts(s1);

cout<<"\n\n";

}

void operator =(string x)

{

strcpy(s1,x.s1);

}

};

void main()

{

string obj,obj1;

clrscr();

obj.get();

obj1.get();

obj=obj1;

obj.show();

getch();

}

OUTPUT ::

Enter any string : HAPPY

Enter any string : BIRTHDAY

The copied String is : BIRTHDAY

Write an OOP program to overload < (less than) operator to find which of the two string object is

greater and

show the greater string object.

SOURCE CODE ::

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

#include<string.h>

class string

{

char s1[20];

public:

void get()

{

cout<<"\n\n Enter any string : ";

gets(s1);

}

void show()

{

cout<<"\n\n Greater String is : ";

puts(s1);

cout<<"\n\n";

}

int operator <(string x)

{

int l1=strlen(s1);

int l2=strlen(x.s1);

Page 62: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

if(l1>l2)

return(1);

else

return(0);

}

};

void main()

{

string obj,obj1;

clrscr();

obj.get();

obj1.get();

if(obj<obj1)

{

obj.show();

}

else

{

obj1.show();

}

getch();

}

OUTPUT ::

Enter any string : FOURTH

Enter any string : SEMESTER

Greater String is : SEMESTER

Type Conversion

//conversion distance to float ,float to distance

#include<iostream.h>

#include<conio.h>

class temp

{

private:

int f;

float i;

public:

temp()

{ f=0;i=0; } //Null Constructor

temp(int x,float y)

{ f=x; i=y;} //Argument Constructor

//From Basic to user defined

temp(float m) //one arg constructor

{ float fe=3.2*m;

f=int(fe);

i=12*(fe-f);

}

void getdata()

{

cin>>f;

cin>>i;

}

Page 63: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

void show()

{ cout<<f<<i; }

//From user defined to basic

operator float()

{

float fr=i/12; //convert to inch

fr=fr+float(f);

return fr/3.2;

}

};

void main()

{

temp t1=2.35; //convert float to distance

clrscr();

cout<<"\n temp1 =";

t1.show();

t1=1.0;

cout<<"\ntemp1= ";

t1.show();

temp t2(5,10.25);

float mtrs=float(t2); //converts distance to float

cout<<mtrs;

mtrs=t1;

cout<<mtrs;

getch();

}

//conversion object of differnt classes

#include<iostream.h>

#include<conio.h>

#include<math.h>

class rec

{

private:

float x;

float y;

public:

rec()

{ x=0.0;

y=0.0;

} //Null Constructor

rec(float x1,float y1)

{ x=x1; y=y1;} //Argument Constructor

void display()

{

cout<<x<<y;

}

};

class polar

{

private :

Page 64: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

float r;

float angle;

public :

polar()

{ r=0.0;angle=0.0; }

polar(float r1,float angle1)

{ r=r1;angle=angle1; }

void display()

{

cout<<r<<angle;

}

operator rec()

{

float x2=r*cos(angle);

float y2=r*sin(angle);

return rec(x2,y2); //constrctor call

}

};

void main()

{

rec Rec;

polar pol(10.0,0.456);

Rec=pol;

cout<<pol.display();

cout<<Rec.display();

getch();

}

INHERITENCE

Inheritance :-

“The mechanism of deriving a new class from an old class is called inheritance or derivation”

The old class is referred to as base class and the new one is called the derived class. The derived

class inherits some or all the properties from the base class.

1. It’s a method of implementing reusability of Classes.

2. The Members of one Class can be accumulated in another Class through Inheritance.

3. The Class which acts as the source of providing its Members for Inheritance is called the

Parent or Base Class. The Class that derives from or acquires the Members of Base Class is

called the Child or Derived Class.

4. The Private members of any Class can Not be Inherited.

5. It adds some enhancement to the base class.

Single Inheritance: -

Page 65: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

The mechanism of creating a new class from en existing base

class is called single inheritance.

A

B

Base class

Derived class

Multiple Inheritance: -

The mechanism of creating a new class from several base

classes is called multiple inheritance.

Base class

Derived class

A B

C

Multilevel inheritance: -

The mechanism of deriving a class from another derived class

is known as multi level inheritance. The following is an

example.

Base class

Derived class

A

B

C Derived class from the

derived class ‘B’

Hierarchical Inheritance: -

The mechanism of deriving more than one derived class from

one base class. This process is known as hierarchical

inheritance. The following is an example.

Base class

Derived classes

A

B C D

Hybrid inheritance:

The mechanism of deriving a class from other derived classes,

which are, derived from the same base class. The following is

an example

Defining derived classes: - A class that uses inheritance to gain the behavior and data of another

('base') class is called derived class. A derived class is defined by specifying its relation ship with

the base class in addition to its own details. The general form of defining a derived class is as

follows.

Class derived class_name : visibility-mode base-class-name

{

members of derived class;

-----------

};

1) Public Inheritance :- Here the Child Class acquires the Protected and Public Members. And

they Remain

Protected and Public in the Child Class. Its done by using “public “ keyword during Child

Class definition.

Each public member in the base class is public in the derived class.

Each protected member in the base class is protected in the derived class.

Each private member in the base class remains private in the derived class.

Class base-class name{ };

class child-class-name : public parent-class-name { definition of the child class};

Grand parent

Parent - 1 Parent - 2

Child

Page 66: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Private Inheritance :- Here the Child Class acquires the Protected and Public Members. And

they

Become Private in the Child Class. Its done by using “private “ keyword during Child

Class definition.

Each public member in the base class is private in the derived class.

Each protected member in the base class is private in the derived class.

Each private member in the base class remains private in the derived class and hence it is

visible only in the base class.

class base-class name{ };

class child-class-name : private parent-class-name { definition of the child class};

3) Protected Inheritance :- Here the Child Class acquires the Protected and Public

Members. And they Become Protected in the Child Class. Its done by using “protected

“ keyword during Child Class definition.

Each public member in the base class is protected in the derived class.

Each protected member in the base class is protected in the derived class.

Each private member in the base class remains private in the derived class

class base-class name{ };

class child-class-name : protected parent-class-name { definition of the child class};

Single Level Inheritance :-

1) Here there is one Base Class and one Derived Class.

2) Syntax :- class child-class-name : <access-mode> parent-class-name { definition

code for the child class } ;

Example :

#include<iostream.h>

#include<conio.h>

class A

{

char name[20];

int roll;

public:

void getbase()

{ cout<<"enter roll and name:";

cin>>roll>>name;

}

void showbase()

{ cout<<"\nname="<<name<<"\nroll="<<roll;

}

};

class B:public A

{float h,w;

public:

void getd()

{ getbase();

cout<<"enter height and weight:";

Page 67: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cin>>h>>w;

}

void showd()

{ showbase();

cout<<"\nheight="<<h<<"\nweight="<<w;

}

};

void main()

{

clrscr();

B b;A a ;

//a.getbase();

b.getbase();

b.getd();

b.showd();

//a.showbase();

getch();

}

Multiple inheritances: - Multiple-inheritance is a mechanism of deriving a new class from two

or more base classes. In multiple-inheritance there will be only one derived class and more than

one base class’s.

Multiple-inheritance allows us to combine the feature of several existing classes for defining new

classes. The syntax of a derived class with multiple base classes is as follows.

Class D: Visiblity B-1, Visibility B-2...

Using comma operator to separate the base classes, Suppose if you create an object of a derived

class then first it call the constructor of class B-1 and then call constructor of class B-2 then call

the constructor of derived class. Similarly the first the destructor of the derived class is called and

then call the destructor of the class B-2 and then call destructor of class B-1 to destroy the object

of the derived class. The order of calling is always depend on the order of derivation. Suppose if a

base class is derived as virtual then at first the virtual class constructor is called then call the

remaining class constructor declared in the order

class m

{

protected : int m;

public : void get m( )

{ cout<<“enter m value “;

cin>>m;

}

};

class N

{

protected: int n;

public : void getn( )

{ cout<<“enter n value”;

cin>>n;

}

};

Page 68: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

class P: public M, public N

{

public : void display ( )

{ cout<<“m=”<<m endl;

cout<<“n=”<<n<< endl;

cout<<“mxn=”<<m*n<<endl;

}

};

void main( )

{

P p;

p.getm( );

p.getn();

p. display( );

getch( );

}

input of the above program;

enter m value = 20

enter n value =10

output of the above program m=20

n=10

m*n=200

Multi level inheritance: -

“The mechanism of deriving a new class from existing derived class is called multi level

inheritance”. The object of the derived class is having a capability to access base class and

intermediate base class data members and member functions.

Base class

Derived classes

A

B

C

Intermediate class

# include<iostream.h>

class student

{

protected :

int rno ;

char name[20];

public:

void get()

{cout <<"enter roll no. and name";

cin>>rno>>name;

}

void show ()

{

cout<<"Roll number:"<<rno<<”Name:”<<name<<endl;

}

};

Page 69: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

class test : public student

{

protected :int m1, m2;

public : void getmarks ( )

{

cout<<"enter marks in 2 subjects";

cin>>m1>>m2;

void showmarks ( )

{

cout<< "subject1:"<<m1;

cout<<"subject 2:"<<m2;

}

};

class final : public test

{

private : float total;

public: void display ()

{

total= m1+m2;

show( );

showmarks ( ) ;

cout<<"Total:"<<total;

}

};

void main ( )

{ final f

f.get( );

f.getmarks ( );

f.display ( );

}

Hybrid inheritance:- The mechanism of deriving a new class from more than one form for

inheritance is called hybrid inheritance. In some situations we need to apply 2 or more types of

inheritances in the design of our program. For example consider the following hierarchy of

classes.

1) It’s a combination of single-level, multi-level, multiple and hybrid Ineritance.

2) Here the resultant (last or grand-child) Child class in the structure can acquire

duplicate copies from the grand parent class.

In situations where the resultant child class can acquire duplicate copies of the grand

parent class then grand parent class used during inheritance is accompanied with “

virtual “ keyword, to avoid duplicity in the grand child class.

Pointer to Object

#include <iostream.h>

class item

Page 70: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

int code;

float price;

public:

void getdata(int a,float b)

{

code = a;

price = b;

}

void show(void)

{

cout<<"Code : << code<<"\n";

cout<<"Price:"<<price<<"\n";

}

};

const int size = 2;

int main()

{

item *p = new item[item];

item *d = p;

int x,i;

float y;

fpr(i=0; i<size; i++)

{

cout<<"Input code and price for item"<< i+1;

cin >> x>>y;

p->getdata(x,y);

p++;

}

for(i=0; i<size; i++)

{

cout <<"Item:"<<i+1 <<"\n";

d->show();

d++;

}

Page 71: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

return 0;

}

Constructors during Inheritance :-

1) When Inheritance takes place, an unnamed Instance of the Parent Class gets created in

the every Object created from the Child Class.

2) As an Instance of the Parent Class is created, so the constructor of the Parent Class

also gets invoked.

If there is a Default Constructor in the Parent Class then it gets invoked First and then

the Child Class constructor is invoked.

5) If any base class contains a constructor with one or more arguments, then it is

compulsorily to have

a constructor in the derived class otherwise it is optional to specify the constructors in

the derived

class. When the program execute first it execute base class constructor and then the

derived class

constructor.

Only the Immediate Child Class Constructor can call the Immediate Parent Class

Constructor to satisfy the compiler.

6) Syntax :- child-class-constructor ( arguments if any ) : parent-class-constructor

(parameters) { definition of the child-class-constructor }

Example: No argument constructor in base and derived class

#include<iostream.h>

#include<conio.h>

class A

{

public:

A()

{ cout<< " i m base class constructor"; }

~A()

{ cout<< " object of base class destroyed";}

};

class B:public A

{ public:

B()

{ cout<<"i m derived class constructor";

}

~B()

{ cout<< " object of derived class destroyed";}

};

void main()

{

clrscr();

B b;

getch();

}

Page 72: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

output:

i m base class constructor

i m derived class constructor

object of derived class destroyed.

object of base class destroyed

Example: Argument constructor in base and derived class

#include<iostream.h>

#include<conio.h>

class base1

{ int x;

public:

base1(){cout<<"\ni m base1 class constructor";}

base1(int a)

{ x=a;

}

void show()

{ cout<<"\nx="<<x;

}

};

class base2

{ int y;

public:

base2(){cout<<"\ni m base2 class constructor";}

base2(int e)

{ y=e; }

void show()

{ cout<<"\ny="<<y; }

};

class B:public base1, public base2

{ int z;

public:

B(){ cout<<"\ni m derived class constructor";}

B(int a,int b,int c):base1(a),base2(b)

{ z=c;}

void show()

{ cout<<"\nz="<<z;}

};

void main()

{

clrscr();

B b1;

B b(12,34,78);

b.show();

b.base1::show();

b.base2::show();

getch();

}

output:

Page 73: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

i m base1 class constructor.

i m base2 class constructor.

i m derived class constructor.

z=78

x=12

y=34

Accessing private members of base class in the derived class by using friend class

A public member function of a base class can access the private member of the derived

clas irrespective of the friend class has been derived privately or publicly.

Example: A friend class derived privately.

Class base

{ friend class derived;

private:

int count;

base( ):count(0)

{ }

};

class derived : private base

{ public:

void show()

{ cout<<”count=”<<++count; //valid

}

};

void main()

{ derived d1;

d1.show();

getch();

}

Note: If we derive another class from base and try to access the private data member count then

there

will be an error.

class der2:public base

{ public:

void show()

{ cout<<”count=”<<++count; //error , can not access the private data member.

}

};

NOTE: Ambiguity in hybrid inheritence.

#include<iostream.h>

#include<conio.h>

class base

{ protected:

int a,b;

Page 74: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

public:

void get()

{ cout<<"enter a=";

cin>>a;

cout<<"enter b=";

cin>>b;}

void show()

{ cout<<"a="<<a<<"\nb="<<b;}

};

class d1 : public base

{ protected :int c;

public:

void get1(){cout<<"enter c=";

cin>>c;}

void show1()

{ cout<<"\nc="<<c;

}

};

class d2 : public base

{ protected:int d;

public:

void get2(){cout<<"enter d=";

cin>>d;}

void show2()

{ cout<<"\nd="<<d;

}

};

class child : public d1,public d2

{ int e;

public:

void get3(){cout<<"enter e=";

cin>>e;}

void show3()

{ cout<<"\ne="<<e;

}

};

void main()

{ clrscr();

child c1;

//c1.base::get();

//c1.base::show();

c1.get(); //error member is ambiguous

c1.show(); //error member is ambiguous

//c1.d1::get();

//c1.d2::get();

//c1.d1::show();

//c1.d2::show();

c1.get1();

c1.show1();

c1.get2();

Page 75: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

c1.show2();

c1.get3();

c1.show3();

getch();

}

Virtual Base Class:

The mechanism of deriving a class from other derived classes, which are, derived from the same

base class, is called multipath inheritance. An object of multipath inheritance having two sets of

grand parent class members. They are one from parent -1 and the other form parent-2. The

compiler generates ambiguity in function call if you try to call grand parent members using child

object. The duplication of inherited members due to multiple paths can be avoided by making the

common base class as virtual base class.

class grand parent

{

-----------

-----------

};

class parent-1:public virtual grand parent

{

-----------

-----------

};

class parent-2 : virtual public grand parent

{

-----------

-----------

};

class child : public parent -1, public parent -2

{ // it will contain only one

-----------

----------- // copy of members of

----------- // grand parent

};

Example:

#include<iostream.h>

#include<conio.h>

class base

{ protected:

int a,b;

public:

void get()

{ cout<<"enter a=";

cin>>a;

cout<<"enter b=";

cin>>b;}

void show()

{ cout<<"a="<<a<<"\nb="<<b;}

Test Sport

Result

Student

Page 76: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

};

class d1 :virtual public base

{ protected :int c;

public:

void get1(){cout<<"enter c=";

cin>>c;}

void show1()

{ cout<<"\nc="<<c;

}

};

class d2 :virtual public base

{ protected:int d;

public:

void get2(){cout<<"enter d=";

cin>>d;}

void show2()

{ cout<<"\nd="<<d;

}

};

class child : public d1,public d2

{ int e;

public:

void get3(){cout<<"enter e=";

cin>>e;}

void show3()

{ cout<<"\ne="<<e;

}

};

void main()

{ clrscr();

child c1;

c1.get();

c1.show();

c1.get1();

c1.show1();

c1.get2();

c1.show2();

c1.get3();

c1.show3();

getch();

}

Pointers to object:

A pointer can point to an object created by a class.

Example:

Class A

{ int a;

public:

void get()

Page 77: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{cin>>a;}

void show()

{ cout<<a;}

};

void main()

{ A a1;

A *p;

ptr=&a1;

p->get(); // or (*p).get(); indirection operator

p->show() // or (*p).show()

}

This Pointer

‘this’ pointer :- ‘this’ pointer holds the address of the instantiated object.

The member functions use this pointer to access the data members of a class. Internally,

the address in this pointer is passed to the member functions through the global ecx

register of the microprocessor.

this pointer stores the address of the class instance, to enable pointer access of the

members to the member functions of the class.

this pointer points to the object for which the member function is currently executing.

This unique pointer is automatically passed to member function when it is called.The

pointer this acts as an implicit argument to all the member functions.

this pointers are not accessible for static member functions.

this pointers are not modifiable.

Example:

#include<iostream.h>

#include<conio.h>

class base1

{ int x,y;

public:

void get()

{ cout<<"enter x and y";

cin>>x>>y;

}

void show()

{ cout<<"\nx="<<x<<"\ny="<<y;

cout<<"\n"<<this;}

};

void main()

{

clrscr();

base1 b1,b2;

b1.get();

b1.show();

b2.show();

getch();

}

Example2:

#include<iostream.h>

Page 78: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

#include<conio.h>

class base1

{ int x,y;

public:

void get()

{ cout<<"enter x and y";

cin>>x>>y;

}

void show()

{ cout<<"\nx="<<this->x<<"\ny="<<this->y; // show the value of x and y; same as

cout<<x<<y;

}

};

void main()

{

clrscr();

base1 b1,b2;

b1.get();

b1.show();

getch();

}

Pointer to Derived Classes :-

1. They are declared as pointers along with the class name as the data-type.

2. To access the members of the class arrow symbol “->” is used.

3. Its observed that the pointer of Parent class can point towards the objects of its Child class.

But a Child class pointer cannot point towards Parent class.

4. Its observed that if pointer of Parent class is assigned address of its Child class then also its

cannot access the members of the Child class object, although it can access the Parent class

members, in such situation we can access only those members which are inherited from the

base class and not the members that originally belong to derived class.

5. Example :-

class Base

{

public:

void show()

{

cout<<"\i m base class function";

}

};

class Derive: public Base

{ int x;

public:

void show()

{ cout<<"\ni m derive class function";

}

void get()

{ cin>>x;}

void show1()

{ cout<<"\n x=”<<x;}

};

main()

Page 79: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

clrscr();

Base b1;

Derive d1;

Base *bp;

bp=&b1;

bp->show(); //This Calls Class Base show()

bp=&d1;

bp->show(); //This also calls Class Base show() Not Class B show()

bp->get(); //error , get is not the member of Base

bp->show1(); //error

((Derive*) bp)->show(); // cast the pointer bp to the Derive type.

//This calls Class derive show() as bp is converted to Derive* type

getch();

}

Note: A derived class pointer can not point to the object of the Base class but it can point to the

objects of the same class.

In above example if we make an object of the derived class then.

main()

{

clrscr();

Base b1;

Derive d1,d2;

Derive *dp;

dp=&d1;

dp->show(); //This Calls Class Derive show()

dp->get();

dp->show1();

dp=&d2;

dp->show(); //This also calls Class Derive show() but for the object d2.

dp->get();

dp->show1();

dp=&b1; // error

((Base*) dp)->show(); // cast the pointer dp to the Base type.

//This calls Class Base show() as dp is converted to Base* type

getch();

}

Function overriding:

When the same function exists in both the base class and the derived class, the function in the

derived class will be executed. (This is true of objects of the derived class. Objects of the base

class don’t know anything about the derived class and will always use the base class functions.)

We say that the derived class function overrides the base class function. This is called the function

overriding. This overriding is avoided by virtual function to achieve run time polymorphism.

Difference between Overloading and Overriding

No Overloading Overriding

1 Relationship between methods available in

the same class.

Relationship between a super class

method and a subclass method.

2 Does not block inheritance from the super Blocks inheritance from the super class.

Page 80: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

class.

3 Separate methods share (overload) the

same name.

Subclass method replaces (overrides)

the super class method.

4 Different method signatures. Same method signatures.

5 May have different return types. Must have matching return types.

6 May have different declared exceptions. Must have compatible declared

exceptions.

Run time polymorphism: - Run time polymorphism achieved by using virtual functions. In this

case the function is linked with a particular class at run time. This process is known as late

binding. It is also known as dynamic binding, because the selection of appropriate function is

done, dynamically at run time.

Virtual Functions :-

1. Virtual functions are defined using the keyword “virtual” before function definition.

2. If we desire to call the Child class function using the pointer of Parent class then :-

1) In both the classes we have to define the function with same prototype.

2) In the Parent class we need to use “virtual” keyword during defining the function.

3) Now when we assign the address of Child class object to the pointer of the Parent

class and using arrow operator we can call the function of the Child class.

1. Polymorphism is the ability to refer to objects of different classes.

2. A single pointer variable may be used to refer (base class pointer) to the objects of

different classes.

3. A base pointer even made to contain the address of a derived class, but it always executes

(links) the functions in the base class.

4. By using virtual functions to make the compiler to ignore the type of the pointer and

choose the member function that matches the type of the object.

5. When we use the same function name in both the base and derived classes the function in

base class is declared as virtual C++ determines which function to use at run time, based

on the type of the object pointed to by the base pointer rather than the type of the pointer.

Rules for declaring virtual function:

(1) The virtual function must be member of some class.

(2) It can not be static.

(3) They are accessed by using object pointer .

(4) A virtual function can be friend of another class.

(5) The prototype of the base class version of the virtual function and all the derived

class version must be identical. If the two function with same name but different

prototype , c++ consider them as overloaded function and the virtual mechanism is

ignored.

(6) We can not have virtual constructor but we can have virtual destructor.

Example:

#include<iostream.h>

#include<conio.h>

class Base

{

public:

virtual void display ()

{cout << "\n Display base ";}

Page 81: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

virtual void show()

{cout << "\n show base";}

};

class Derived : public Base

{

public:

void display()

{cout <<"\n Display derived";}

void show()

{cout <<"\n show derived" ;}

};

class Derived1 : public Derived

{

public:

void display()

{cout <<"\n Display derived1";}

void show()

{cout <<"\n show derived1" ;}

};

void main()

{

clrscr();

Base B;

Derived D;

Derived1 d1;

Base *bptr;

cout <<"\n bptr points to Base \n";

bptr = &B;

bptr ->display(); //calls Base version

bptr ->show(); //calls base version

cout <<"\n\n bptr points to Derived\n";

bptr = &D;

bptr -> display(); //calls derive version

bptr ->show(); //calls Derived version

cout <<"\n\n bptr points to Derived1\n";

bptr = &d1;

bptr ->display(); //calls derive version

bptr ->show(); //calls Derived version

getch();

}

OUTPUT:

bptr points to Base

Display base.

Show base

bptr points to Derived

Page 82: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Display Derived.

Show Derived.

bptr points to Derived1

Display Derived1

Show Derived1.

Pure Virtual Functions and Abstract Classes :-

Pure virtual function:-

The virtual function having no body and initialized to zero is called pure virtual functions..

A class containing pure virtual function is called abstract classes or pure abstract classes.

Where as all other classes without pure virtual function and which are instantiated are called as

concrete classes.

1. These are the functions that are declared as Virtual at the same time assigned to Zero value.

2. They don’t have any definition, they are only declared and equated to Zero.

3. If a Class contains one or more Pure Virtual functions then that Class becomes Abstract.

4. Objects of Abstract classes can Not be created.

5. If we Inherit an Abstract class then we have to Redefine all the Parent class Pure Virtual

functions in the Child class, otherwise the Child class would also become an Abstract class.

6. Syntax :- virtual function-name ( parameter list ,if any ) = 0 ;

7. Overriding is strictly essential.

Abstract class: is an incomplete class and hence no object of such class can be created.

The main objective of an abstract base class is to provide some behavior or characteristics to the

derived classes and to create base pointer required for the achieving run time polymorphism.

Exmple: /* A pure virtual function is a virtual function with no body */

#include<iostream.h>

#include<conio.h>

class shape

{ public:

virtual void shapeof()=0;

};

class circle : public shape

{ public :

void shapeof()

{ cout<<"\nDraw circle"; } //Method Overriding

};

class triangle : public shape

{ public :

void shapeof()

{ cout<<"\nDraw triangle"; } //Method Overriding

};

class rect : public shape

Page 83: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{ public :

void shapeof()

{ cout<<"\nDraw rect"; } //Method Overriding

};

void main()

{ clrscr();

circle c;

triangle t;

rect r;

shape *p[3];

p[0]=&c ;

p[1]=&t;

p[2]=&r;

for(int i=0;i<3;i++)

p[i]->shapeof();

getch();

}

Memory management operators :-

Memory management means the way of allocating part of a memory to program at their request,

and freeing it for reuse when no longer needed. In C++ unary operators ‘new’ and ‘delete’ are

used to allocate and free the dynamic memory, they are also called as free store operators.

new:

Pointer variable = new data type;

Here pointers variable is a dynamic variable of type pointer.

The unary operator new is used to allocate required memory at runtime. There are three stages to

allocate required memory they are

12. Locates and reserves storage for the object or objects to be allocated.

13. Initializes the object(s) using class constructor

14. Returns a pointer to the object(s) of a pointer type derived from type-name.

Page 84: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

The ‘new’ operator allocates sufficient memory to hold data and return its address. If the object is

of type array it returns the base address of an array. The memory allocated by using new operator

is not initialized. If the required amount of memory is not allocated the operator new throws an

exception to set_new_handler() function. The memory allocated by using new operator

Ex: 1) int *p,*q;

p= new int;

q= new int;

We can combine the declaration of pointers and their assignments as follows.

2) int *p = new int;

float *x = new float;

Now we can use the above pointers as follows.

*p =15; *x = 18.9;

We can also initialize the memory using the new operator as follows

3) int *p = new int (10);

Thus *p will contain value ‘10’

We can also create one-dimensional array by using new operator as follows.

4) int *p = new int [10];

The above statement creates a memory space for an array of 10 integers hence p[0] will refer

the first element. p[1] to the second element and so on.

Delete:

When a data object is no longer needed, it is destroyed to release the memory space for reuse. The

unary operator delete is used to release the memory allotted by using new operator. The delete

operator does not return any value. When delete is used to deallocate memory for a C++ class

object, the object's destructor is called before the object's memory is deallocated (if the object has

a destructor). The general form of delete operator is

delete (ptrvarible); Where ptrvaribale is having a dynamic memory allocated using new

For example:

delete P - If P is a pointer variable then it will be destroyed after executing this statement

To free a dynamically allocated array by using

delete [size] pointer variable; the size specifies the Number of elements in the array to be

free

To free all the allocated memory location of an array by using

delete[](pointer variable) In this case it is not required to give the size of the array.

At hear the [ ] tell the compiler the released memory is of type pointer. Only one pair of [ ]

are sufficient to release memory for any dimension.

Example:

#include<iostream.h>

#include<conio.h>

void main()

{ clrscr();

int *p_i=new int;

float *p_f=new float;

char *p_c=new char;

Page 85: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

int *p_a=new int[5];

cout<<"\nEnter any integer value:";

cin>>*p_i;

cout<<"\nEnter any float value:";

cin>>*p_f;

cout<<"\nEnter any characte value:";

cin>>*p_c;

cout<<"\nenter aaray elements:";

for(int i=0;i<5;i++)

cin>>p_a[i];

cout<<" \ninteger value is:"<<*p_i;

cout<<" \nfloat value is:"<<*p_f;

cout<<" \ncharacter value is:"<<*p_c;

cout<<"\nelements are:";

for(i=0;i<5;i++)

cout<<p_a[i];

delete p_i;

delete p_f;

delete p_c;

delete p_a;

getch();

}

Page 86: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Console, Disk I/O Operations and Templates

Manipulator functions:

Manipulators are special functions that are specifically designed to modify the working of a

stream. They can be embedded in the i/o statements to modify the form parameters of a stream.

there can be more than one manipulator in a statement and they can be chained. The main

advantage of using manipulator function is that they facilitate the formatting of input and output

stream. Manipulators are categorized into two types.

Non-parameterized manipulators

Parameterized manipulators

Non-parameterized manipulators are

dec, hex, oct, ws, endl,ends,flush

Parameterized manipulators:

setw(int width), setprecision(int prec), setfill(int fchar), setbase (int base),

setiosflags(long flags), resetiosflags(long flags).

The following are the list of standard manipulators. To carry out the operations of these

manipulator functions in a user program, the header file input and output manipulator

<iomanip.h> must be included.

endl: the endl is an out put manipulator to generate carriage return or line feed character. The endl

may be used several number of times in a c++ statement

For example: 1. cout << “a” << endl;

A program to display a message on tow lines using the endl manipulator and the

corresponding output is given below

#include <iostream.h>

void main()

{ cout << “this is the test “ <<endl;

cout << “program “ ; }

output this is the test

program

The endl is same as the non-graphic character to generate line feed (\n)

setbase(): the setbase() manipulator is used to convert the base of one numeric value into another

base.

Following are the common base converters in C++

dec - decimal base (base 10)

hex - hexadecimal base (base 16)

Page 87: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

oct - octal base (base 8)

In addition to the conversion facilities such as bases like dec, hex, oct, the setbase manipulator is

also used to define the base of a number as a numeric value. The prototype setbase() manipulator

is defined in the iomanip.h header file and it should be included in user program. The hex, dec,

oct manipulators change the base of inserted or extracted integer values. The original default

manipulator for stream input and output is dec.

Example

The program to show the base of a numeric value of a variable using setbase manipulator function

#include <iosteam.h>

#include <iomanip.h>

void main()

{ int value;

cout << “enter the values “<<endl;

cin >> value;

cout <<”decimal base = “ << setbase(10)<< value <<endl;

cout << “hexadecimal base =” <<setbase(16) <<value <<endl;

cout << “octal base “ <<setbase(8) <<value <<endl;

}

setw()

The setw() stands for the setwidth. The setw manipulator is used to specify the minimum

number of character positions consumed on the output field of a variable.

The general format of the setw manipulator function is setw(int w)

This changes the field width to w, only for the next insertion. The default field width is 0

For example:

cout << setw() <<a <<endl

cout << setw(10) <<a <<endl;

setfill()

The setfill() manipulator is used to specify a different character to fill the unused field width of

the value.

The general syntax of the setfill(n) manipulator is setfill(char f)

Which changes the fill character to f. the default fill character is a space.

For example setfill(‘*’) // fill a asterisk(*) character.

setprecision(int prec) : sets the precision used for floating point output. The number of digits to

be shown after the decimal point is given by the integer prec.

For example:

#include <iostream.h>

#include <iomanip.h>

void main()

{ float f = 123.23456;

cout << setprecision(3) << f <<endl;

}

out put : 123.234

FILE:

File is a collection of records and record is a collection of data items. These data items may be

any one of the valid information. File stream is a stream of information passing between i/o

devices. This information may be a data or may be an object of a class.

Page 88: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

I/O Streams :-

1. A Stream is a queue of memory spaces or buffers that are used to connect I/O Devices and

Disk Files with our programs.

2. We use Input Streams to connect our program with Input Devices or to Receive data from

Disk Files.

3. We use Output Streams to connect our program with Output Devices or to Write data in to

Disk Files.

4. All the I/O Streams are in the form of inbuilt Classes.

5. The Stream Class use for receiving input from any Input Device ISTREAM and from Disk

File is IFSTREAM (which is derived form ISTREAM class).

6. The Stream Class use for sending output to any Output Device OSTREAM and to Disk File

is OFSTREAM (which is derived form OSTREAM class).

7. All the Input and Output Stream Classes are Inherited from the grand parent IOS Class.

8. The IOSTREAM class for I/O Devices is derived from multiple inheritance from ISTREAM

and OSTREAM classes.

10 The FSTREAM class for Disk Files is derived directly from IOSTREAM class.

Inbuilt Formatted Console Output functions :-

1. The inbuilt console Output operations can be used to set Format of how the output would

appear.

2. All the console I/O functions are available in IOSTREAM class. Using “cin” object we can

access the Input functions and using “cout” object we can access the Output functions.

3. Functions and their Use :-

Functions Use

cout.setf(ios::left ) ; For displaying the matter using cout, as Left Justified

cout.setf(ios::right ) ; For displaying the matter using cout as Right Justified

cout.setf(ios::scientific) ; For displaying the matter using cout in exponential (e

) format.

cout.setf(ios::oct ) ; For displaying the matter in Octal format.

cout.setf(ios::hex ) ; For displaying the matter in Hexadecimal format.

cout . fill ( char ) ; For displaying the specified characters instead of

blank spaces.

Page 89: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cout . width ( int ) ;

Setting the number of columns in which the content

has to be displyed. If the content length is less than the

specified columns then the content will be justified

according to the sef() function. If the columns

specified is less than the matter length them the width

is ignored and the full content is displayed. By default

its left justified.

cout . precision ( int ) ; It specifies the number of digits to be displayed after

the decimal points.

cout . unsetf ( float ) ; It resets the given “ ios : “ settings that are set using

setf () function above it.

Inbuilt Disk I/O Functions :-

1. The Disk I/O functions are needed to Read and Write into Disk files ( Hard-disk).

2. The Inbuilt Disk I/O Functions are available in FSTREAM class, so we need to #include <

fstream.h> header file.

3. Here the basic point of understanding of reading and writing should be only with respect to

the Program we are writing.

4. If we say that we are Outputting data, then it means we are Writing data into a Disk File

from our Program.

5. If we say that we are Inputting data, then it means we are Reading data from a Disk File to

our Program.

6. Steps to be followed when using Disk files :-

i ) We create an fstream Object.

ii ) Using the fstream object now we open the specified File with specified

Mode (Input, Output or Both).

iii ) Using the inbuilt member functions of the fstream object we perform the

Reading or Writing operations.

iv ) Before finishing, we close the file and the stream through which the file is

attached to our program, by using the close() function along with the fstream object.

Member functions of FSTREAM class and their Use

Functions Use

open ( name-of-file-in-double-quotes, mode ) For opening the specified File,

whose name is given as a string

in double quotes as the First

Page 90: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

argument and in the specified

Mode given as the Second

argument

close () Closes the file for stopping any

further use.

put (char) Writes one character at a time

into the File, from the value of

the char variable as the given

argument.

get (char) Reads one character at a time

from a File, into the char

variable as the given argument.

write ((char*) &variable , sizeof (variable ) ) Its used to write data of any

data-type into the File, from the

value of the variable given as

the first argument.

read ((char*) &variable , sizeof (variable ) ) Its used to read data from the

File into the variable given as

the First argument.

eof(void) Returns true (non zero value)

when EOF is encountered.

fail() Returns true (non zero value)

when the file operation done

immediately before, had Failed.

Opening a file: A file can be open in two ways :

Page 91: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

(i) using the constructor function of the class ( when using one file)

(ii) using the member function open() of the class (when using multiple

files)

Following are some Pointers and Indicators associated with Files :-

i ) Beginning Of File (BOF) Indicator :- This indicator helps to identify the Beginning of File.

Represented by :- ios :: beg

ii )Current Position in File Indicator :- This indictor helps to identify the Current position

where

we are presently operating in the File.

Represented by :- ios :: cur

iii )End Of File (EOF) Indicator :- This indicator helps to identify the End of File.

Represented by :- ios::end

iv) Get Pointer :- The Get Pointer is used automatically when we are Reading contents from a

File. The

Get pointer gets incremented automatically as soon as we read contents of the File. We

can also

manually set its position.

Accessed by following functions :-

tellg(void) :- Gives the current position of the Get Pointer in the File.

seekg (moving-distance from starting-position , starting-position indicted by the

indicator used ) It moves the Get pointer to the distance indicated by the first argument from the reference

position

indicated by the second argument.

v )Put Pointer :- The Put Pointer is used automatically when we are Writing data into a File.

The Put pointer

gets incremented automatically as soon as we write data into the File. We can also

manually set its

position.

tellp(void) :- Gives the current position of the Put Pointer in the File.

seekp (moving-distance from starting-position , starting-position indicted by the

indicator used) It moves the Put pointer to the distance indicated by the first argument from the reference

position

indicated by the second argument.

vi )The Reading and Writing would take place from the Current Positions of Get and Put

pointers respectively.

Templates: - A template can be used to create a family of classes or functions. A template can be

considered as a kind of Marco. Template can be defined as class or function parameterized by a

set of type parameters, values, or templates. The type parameters in the template definition are

Page 92: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

replaced by specified data type at runtime. The templates are some times called parameterized

classes or functions.

Class templates: -

Class template is a class parameterized by type parameters, values, or templates. To utilize the

class template the template arguments must be passed at the time of instantiation.

The following is the general form of defining class templates.

template <class T>

class name

{

class member specification

with anonymous type T

where ever appropriate.

};

A class created from a class template is called a template class. The syntax of defining an object

of a template class is as follows.

class name <data type> object;

Function Templates

• When a single function is written for a family of similar functions, it is called as a

‘functions template’. In this function at least one formal argument is generic.

• When a single function is written for a family of similar functions, they are called as

function repetition of the source code. The main advantage of using function template is

avoiding unnecessary repetition of the source code. The object code becomes more

compact and efficient than the conventional way of declaring and defining the functions.

• Secondly, full data type checking is carried out. The function template does not specify the

actual data types of the arguments that a function accepts but it uses a generic or

parameterized data type. In a function template at least one formal argument is generic.

The general syntax of the class template is,

Template <class T>

Class user_defined_name

{

Private:

________________

________________

Public:

_______________

_______________

};

Example:

//using function template

#include <iostream.h>

template <class T> T square (T one)

{

return (one*one);

}

Page 93: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

int square (int );

float square (float);

double square( double);

void main()

{

int x,xsq;

float y,ysq;

double z,zsq;

cout <<"enter an integer \n";

cin >> x;

cout <<"enter a floating point number ?\n";

cin >> y;

cout <<"enter a double precison number \n";

cin >>z;

xsq = square(x);

cout <<"x = " << x << "and its square = "<<xsq<< endl;

ysq = square(y);

cout<< "y"<<y<<"and its square ="<<ysq << endl;

zsq = square(z);

cout <<"z=" << z<<" and its square ="<<"zsq=" <<zsq<< endl;

}

Example-2

//using function template

#include <iostream.h>

template<class T>

T swap (T &first, T &second)

{

T temp;

temp = first;

first = second;

second = temp;

return(0);

}

int swap (int &a,int &b);

float sum(float &a, float &b);

void main()

{

int ix,iy;

float fx,fy;

cout <<"enter any two integers \n";

cin >>ix >> iy;

cout <<"enter any two floating point numbers ? \n";

cin >>fx>>fy;

swap(ix,iy);

cout <<"after swapping integers \n";

cout <<"ix= "<<ix<<"iy ="<<iy<< endl;

swap (fx,fy);

cout <<" afte swapping floating point numbers \n";

Page 94: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cout <<"fx = "<<fx<<"fy="<<fy<< endl;

}

Exception Handling

• The two most common types of bugs are logic errors and syntactic errors. The logic errors

occur due to poor understanding of the problem and solution procedure. The syntactic

errors arise due to poor understanding of the language itself. We can detect these errors by

using exhaustive debugging and testing procedures .

• WE often come across some peculiar problems other than logic or syntax errors. They are

known as exceptions. Exceptions are run time anomalies or unusual conditions that a

program may encounter while executing. Anomalies might include conditions such as

division by zero, access to an array outside of its bounds, or running out of memory or

disk space

Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions.

Errors such as “out-of-range index” and “over-flow” belong to the synchronous type

exceptions. The errors that are caused by events beyond the control of the program (such as

keyboard interrupts) are called asynchronous exceptions. The exception handling

mechanism in C++ is designed to handle only synchronous exceptions

• The purpose of the exception handling mechanism is to provide means to detect and report

an “exceptional circumstance” so that appropriate action can be taken. The mechanism

suggests a separate error handling code that performs the following tasks.

1)Find the problem (Hit the exception)

2)Inform that an error has occurred (Throw the exception)

3)Receive the error information (Catch the exception)

4)Take corrective actions (Handle the exception)

• The catch block that catches an exception must immediately follow the try block that

throws the exception. The general form of these two blocks are as follows:

• Try

{

…….

Throw exception ; //Block if statements which

………… //detects and throws an exception

………..

}

Catch (type arg) //Catches exception

{

…… //Block of statements that

………. //handles the exception

…….

}

Page 95: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Assignment -1

1. Write down difference between POP and OOP.

Answer:-

Difference between Procedural Programming and Object Oriented Programming

No Procedural Programming Object oriented Programming

1 It is a Top-Down approach. It is a Bottom-Up approach.

2 PP basically consists of writing a list of

instructions for the computer to follow, and

organizing these instructions into groups known

as functions.

OOP allows decomposition of a problem into

a number of entities called objects and then

builds data and functions around these

objects.

3 This paradigm is:

“Decide which procedures you

want; use the best algorithms you can find”.

This paradigm is:

“Decide which classes and

objects are needed; provide a full set of

operations for each class”.

4 Languages support this paradigm by providing

facilities for passing arguments to function and

returning values from functions.

Languages support this paradigm by creating

objects and send the messages to them to use

or manipulate the attributes.

5 Importance given to algorithms rather than data. Importance given to data rather than

algorithms.

6 Data move openly around the system from

function to function.

Data cannot move openly around the system

as the concept of data hiding is involved.

7 E.g. C, COBOL, FORTRAN. E.g. C++, JAVA.

8 Relationship of data and functions is:

Organization of data and functions in OOP:

Object A Object B

Communication

Object C

9 The primary focus is on functions. The primary focus is on objects.

10 It is suitable for creating medium size projects. It is suitable for creating large size projects.

11 It does not model real world problems very well. It can model real world problems.

12 The complexity of the programs is very high. The complexity of the programs is less.

Global Data

Function-1 Local Data

Function-2 Local Data

Data

Functions

Data

Functions

Functions

Data

Page 96: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

2. Explain structure of C++ program.

Answer:-

Structure of the C++ Program :

Simple C++ Program

// my first program in C++

#include <iostream>

void main ()

{

cout << "Hello World!";

}

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered

comments and do not have any effect on the behavior of the program. The programmer

can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is.

C++ supports two ways to insert comments:

// line comment

/* block comment */

#include <iostream>

Lines beginning with a pound sign (#) are directives for the preprocessor. They are not

regular code lines with expressions but indications for the compiler's preprocessor. In this

case the directive #include <iostream> tells the preprocessor to include the iostream

standard file. This specific file (iostream) includes the declarations of the basic standard

Page 97: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

input-output library in C++, and it is included because its functionality is going to be used

later in the program.

void main ()

This line corresponds to the beginning of the definition of the main function. The main

function is the point by where all C++ programs start their execution, independently of its

location within the source code. It does not matter whether there are other functions with

other names defined before or after it.This function's definition will always be the first

ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.

cout << "Hello World";

This line is a C++ statement.This statement performs the only action that generates a visible effect in our first program.

cout represents the standard output stream in C++.The operator << is called the insertion

or put to operator and the meaning of the entire statement is to insert a sequence of

characters (in this case the Hello World sequence of characters) into the standard output

stream (which usually is the screen).

We could have written:

int main () { cout << "Hello World"; return 0; }

Notice that the statement ends with a semicolon character (;). This character is used to

mark the end of the statement and in fact it must be included at the end of all expression

statements in all C++ programs.

3. Write short note on compiling and linking process of c++ program.

Answer:-

Compiling And Linking : Compiling and linking a C++ program depends on compiler and

operating system.Turbo C++ and Borland C++ provide an integrated program development

environment under MSDOS .They provide built in editor and a menu bar which includes options

such as File, Edit, compile and Run.

Page 98: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Prepared By:-Guru

C++ Compilation

• Figure 1.1

C++

Program

C

Code

Object

Code

Execut-

able

C++

COMPILER

NATIVE

C++

TRANSLATOR

LINKER

C

COMPILER

C++

Program

4. Write short note on functions in c++.

Functions in C++ : A complex parts may be decomposed into a small or easily manageable parts

or modules called functions. Functions are very useful to read, write, debug and modify the

complex program. Functions are used to implement reusability of code .

The main Function: In C++ the main() function returns a value of type int to the operating system.

int main()

{

…………

…………….

return 0;

}

Steps of writing Functions :-

1. Function Prototyping :- Here we write the Function prototype, which represents the name of

function, number of input arguments and data-types of input arguments. The prototype describes

the function interface to the comiler.

Syntax :- return-data-type function-name ( input-argument-list along with their data-

types) ;

Example :- int add (int, int) ;

2. Function Definition :- Here we use along with the prototype, Opening and Closing curly

brackets, inside which we write the code of the function.

Syntax :- return-data-type function-name ( input-argument-list along with their data-

types) { …. }

Example :- int add (int a, int b) { return (a+b) ; }

3. Function Calling :- Here we use the function prototype, with out the return type and passing in

the real arguments. It causes the function to execute its code.

Syntax :- function-name ( argument-values) ;

Example :- add (10 , 20 ) ;

Page 99: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

return statement: The keyword return is used to terminate the function and return a value to its

caller. The return statement may also be used to exit a function without returning a value. The

return statement may or may not include an expression.

Syntax:- return;

return (expression);

Assignment -2

1. Write down difference between structure and class.

Answer:-

Structure Class

Structure can be defined as a collection

of dissimilar data items.

Class can be defined as combination

of data items and functionality applied

on that data

Contains only data member Contains data members and member

function applied on that data

By default all members are public By default all members are private

The size of the structure = size of the

individual data items of a structure

The size of the structure = size of the

individual data items of a class

Separate copy of data members are

created for all structure variables

Separate copy of data members and

only one copy of member functions

are created for class

To create a structure variable use

keyword struct

To create a class variable the keyword

class is optional

It is Not possible to inherit structures It is possible to inherit class

Structure are called as Passive data

item

Classes are called as Active data items

2. Explain nested class.

Nested Class :-

1. Nested Classes are the Classes defined inside a Class.

2. A class is defined within another class is called a nested class.

3. The Outer class is known as enclosing class.

4. Member function of a nested class have no special access to members of an enclosing class.

5. Member function of an enclosing class have no special access to members of a nested class.

6. Object of inner class can be created by using : : operator.

Outer_class: : inner_class obj1;

7. The member function of the nested(inner ) class can be defined outside its scope.

Return_type of fun outer_class: : inner_class: : fun() { }

#include<iostream.h>

#include<conio.h>

class sample

{ public: int a;

class inner

{ public:

int b;

void get_in()

{ cout<<"enter valueof b:"; cin>>b; }

}i2;

Page 100: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

void show_out()

{ i2.b=100;

cout<<"\n**value of a=";

cin>>a;

cout<<"value of b="<<i2.b; }

};

sample a1;

sample: :inner i1;

void main()

{ clrscr();

a1.show_out();

i1.get_in();

i2.get_in(); //undefined symbol i2

getch();

}

Note: if we declare the inner class under private access specifier.

class sample

{ private: int a;

class inner

{ public: int b;

void get_in()

{ }

}i2;

public: void show_out()

{ }

};

although its define under private access specifier ,but its members are public.its members wont be

accessible when we declare them under private access specifer.

e.g class inner { private: int b; void get_in() { } }i2;

Example of nested class:

#include<iostream.h>

#include<conio.h>

class sample

{ private: int a;

class inner

{ public:

int b,c;

void get_in()

{ cout<<"enter value of b,c";

cin>>b>>c; }

void show_in()

{ cout<<"b="<<b<<"c="<<c; }

};

public:

void get1()

{ cout<<"enter a";

cin>>a; }

void show1()

{ cout<<"a="<<a;

inner i1;

i1.get_in();

i1.show_in(); }

};

Page 101: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

sample a1;

void main()

{ clrscr();

a1.get1();

a1.show1();

getch();

}

2. Explain static members with example.

Static data members :-

1. Only a single copy of the Static data members are shared between Objects of the Class.

2. Static data members are initialized using the data type Class-Name and Scope-Resolution

Operator and data member-Name

3. The Static members are declared using “ static “ keyword.

4. The access rule of the data members of a class is same for the static data member also.

5. The Static Data Members should be created and initialized before the main function control

block

begins.

6. Syntax :-

For variables :- static data-type variable-name ;

#include <iostream.h>

#include<conio.h>

class sample

{

static int a; // declaration

public:

void incr( )

{ a=a+1; }

void putdata ( )

{ cout <<"a="<<a<<endl; }

};

int sample::a; //by default initialize with 0

void main ( )

{ sample x,y,z;

y. incr ();

z.putdata( );

}

Example: #include<iostream.h>

#include<conio.h>

int g=10;

class sample

{

int a;

public :

static int b;

void show()

{

b++;

cout<<"\nb = "<<b;

Page 102: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

}

}s1,s2;

int sample :: b;

class other

{ int c;

public:void value()

{ s1.b+=2;

cout<<"\n--b--="<<s1.b;

}

} o1,o2;

void main()

{ clrscr();

s1.show() ;

o1.value();

s2.show();

o1.value();

getch();

}

output:

b=1;

--b--=3

b=4

--b--=6

Static member function:-

Like static member variables we can also have static member functions. A member function that

is declared as static has the following properties.

5. A static member function can have access to only other static members(functions or

variable) declared

in the same class.

6. A static member function can be called using the class name a follows.

a) Class_name : : function_name ( )

7. A static member function also calls the class constructor explicitly.

The differences between a static member function and non-static member functions are as

follows.

A static member function can access only static member(data and member functions)

data and functions outside the class. A non-static member function can access all of the

above including the static data member.

A static member function can be called, even when a class is not instantiated, a non-

static member function can be called only after instantiating the class as an object.

A static member function cannot be declared virtual, whereas a non-static member

functions can be declared as virtual

A static member function cannot have access to the 'this' pointer of the class.

A static or non static member function cannot have the same name.

#include<iostream.h>

#include<conio.h>

class test

{

int code;

Page 103: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

static int count ;

public:

void setcode( )

{ code =++ count; }

void showcode ( )

{cout<<"object_number"<< code<<endl ; }

static void showcount ( ) // static member function.

{ cout <<" count" <<count<<" \n";

cout<<”code =”<<code //error , code is a non static member

function.

}

};

int test :: count;

void main ( )

{

test t1,t2,t3;

t1. setcode ();

t2. setcode ();

test :: showcount ( );

t3. setcode ( );

test:: showcount ( );

t1. showcode ( );

t2. showcode ( );

t3. showcode ( );

}

Output: -

count : 2 count : 3

object number :1object number : 2 object number : 3

4. Explain Friend function with example.

Answer:-

Friend Functions :-

1. Friend functions are Not member functions of any class, but they can access the private,

protected and public members of the class.

2. They are declared using “ friend “ keyword.

3. They Don’t belong to any specific Class.

Code code code t1 t2 t3

count setcode()

showcode() showcount()

1 2 3

3

Page 104: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

4. They can be invoked as ordinary functions, with out using any object.

5. They can be defined outside the Class, here also they are defined like ordinary functions and

Not like member functions.

a. The access specifiers does not effect the visibility of Friend Functions.

b. Usually a friend function receives the object as arguments.

9. Syntax :-

friend return-type function-name ( input-arguments ) ;

10. member function of one class can be defined as friend function of another class.In such case

they are

defined using scope resolution operator as shown below.

class X

{ ………

int fun1(); //member fun of X

};

class Y

{ ………..

…………

friend int X: :fun1();

};

Example:

#include<iostream.h>

#include<conio.h>

class sample

{ int a,b;

public:

void get()

{ cin>>a>>b; }

void show()

{ cout<<a<<b; }

friend void swap(sample s);

};

void swap( sample s1)

{ int temp=s1.a;

s1.a =s1.b;

s1.b = temp;

cout<<”a=”<<s1.a<<”b=”<<s1.b;

}

void main()

{ clrscr();

sample s2;

s2.get();

cout<<” before swapping:”<<endl;

s2.show();

cout<<”After swapping:”

swap(s2); //function call swap(s2) passes the object s2 by value to the friend function.

getch();

}

Page 105: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Assignment -3

1. Write short note on copy constructor.

Answer:-

Copy constructor:- A copy constructor is a special constructor in the C++ programming

language used to create a new object as a copy of an existing object. This constructor takes a

single argument: a reference to the object to be copied.

Normally the compiler automatically creates a copy constructor for each class (known as an

implicit copy constructor) but for special cases the programmer creates the copy constructor,

known as an explicit copy constructor. In such cases, the compiler doesn't create one

There are four instances when a copy constructor is called:

5. When an object is returned by value

6. When an object is passed (into a function) by value as an argument

7. When an object is constructed based on other object (pf same class)

8. When compiler generates a temporary object (as in 1 and 2 above; as in explicit casting,

etc...)

Constructors of a class can be invoked by using existing objects of the class.

Syntax :- obect . class-name :: constructor-function-call ;

#include <iostream.h>

#include<conio.h>

class code

{ int d;

public:

code()

{cout<<"\ndefault constructor";

} // default constructor

code(int a) //constructor -2

{ d=a;

cout<<"\nparameterized contrctr";

}

code(code &x)//copy constructor

{ d=x.d;

cout<<"\ncopy cntrctr";

}

void display( )

{ cout<<"\nd="<<d<<endl;

}

};

void main( )

{ clrscr();

code A(100); //calls constructor - 2

code B(A); //calls copy constructor

code C=A; //calls copy constructor

code D; //calls no argument constructor

Page 106: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

D=A;// It is assignment not initialization hence no copy const. will be called

A.display ( );

B.display ( );

C.display ( );

D.display ( ) ;

getch();

}

11 Write a program to overload “+” operator.

Ans. #include<iostream.h>

class complex

{

float x; // real part

float y; // Imaginary part

public :

complex(){} // default constructor

complex(float real,float imag) //parameterized constructor

{x= real ; y=imag;}

complex operator +(complex);

void display();

};

complex complex ::operator +(complex c)

{

complex temp;

temp.x= x + c.x;

temp.y= y + c.y;

return(temp); // return complex((x+c.x),(y+c.y));// invokes constructor

}

void complex :: display()

{

cout<< x <<"+i"<<y<<"\n";

}

void main()

{

complex c1,c2,c3; // invokes default constructor

c1= complex(2.3,4.5);

c2= complex(2.4,4.6);

c3= c1 + c2; // c1 + c2 means "c1.operator +(c2)"

cout<<"c1 ";c1.display();

cout<<"c2 ";c2.display();

cout<<"c3 ";c3.display();

}

Page 107: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

12 Write a program to overload “=” operator.

Ans. //overloading an assignment operator

#include <iostream.h>

class sample

{

private:

int x;

float y;

public:

sample(){}

sample(int a,float b)

{ x=a;

y=b;

}

void operator = (sample abc);

void display();

};

void sample ::operator = (sample abc)

{

x= abc.x;

y= abc.y;

}

void sample::display()

{

cout<<x<<endl;

cout<<y<<endl;

}

void main()

{

sample obj1(10,13.5);

sample obj2(12,13.7);

obj1=obj2; // obj1.operator =(obj2);

obj2.display();

obj1.display();

}

13 Write a program to overload “delete” operator.

Ans.

#include<iostream.h>

class testing

{

private: int *arrnum;

public: void *operator new(size_t,size)

{

testing *ptr_test;

ptr_test=::new testing;//::new invokes the global new

ptr_testarrnum = new int;// calls :: new

return ptr_test;

}

void operator delete(void *a_num0)

Page 108: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

{

testing *ptr;

ptr_test =(testing*) a_num;

delete (int*) ptr_testarrnum;// calls global delete

::delete a_num;

}

void get_number()

{

for(int j=0;j<=10;j++)

cin>>arrnum[j];

}

void display()

{

for(int j=0;j<10;j++)

cout<<arrnum[j]<<endl;

}

}

void main()

{

testing *ptr_test= new testing ;

cout<<"enter elements of the array"<<endl;

ptr_test->get_data();

cout<<"the elements of array"<<endl;

ptr_test->display();

cout<<"the delete operator deletes the object"<<endl;

delete ptr_test;

}

Page 109: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Assignment -4

Write short note on Inheritence.

Ans. Inheritance :-

“The mechanism of deriving a new class from an old class is called inheritance or derivation”

The old class is referred to as base class and the new one is called the derived class. The derived

class inherits some or all the properties from the base class.

1. It’s a method of implementing reusability of Classes.

2. The Members of one Class can be accumulated in another Class through Inheritance.

3. The Class which acts as the source of providing its Members for Inheritance is called the

Parent or Base Class. The Class that derives from or acquires the Members of Base Class is

called the Child or Derived Class.

4. The Private members of any Class can Not be Inherited.

5. It adds some enhancement to the base class.

Single Inheritance: -

The mechanism of creating a new class from en existing base

class is called single inheritance.

A

B

Base class

Derived class

Multiple Inheritance: -

The mechanism of creating a new class from several base

classes is called multiple inheritance.

Base class

Derived class

A B

C

Multilevel inheritance: -

The mechanism of deriving a class from another derived class

is known as multi level inheritance. The following is an

example.

Base class

Derived class

A

B

C Derived class from the

derived class ‘B’

Hierarchical Inheritance: -

The mechanism of deriving more than one derived class from

one base class. This process is known as hierarchical

inheritance. The following is an example.

Base class

Derived classes

A

B C D

Hybrid inheritance:

The mechanism of deriving a class from other derived classes,

which are, derived from the same base class. The following is

an example

Explain single level inheritance with example.

Ans.

Grand parent

Parent - 1 Parent - 2

Child

Page 110: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Single Level Inheritance :-

1) Here there is one Base Class and one Derived Class.

2) Syntax :- class child-class-name : <access-mode> parent-class-name { definition

code for the child class } ;

Example :

#include<iostream.h>

#include<conio.h>

class A

{

char name[20];

int roll;

public:

void getbase()

{ cout<<"enter roll and name:";

cin>>roll>>name;

}

void showbase()

{ cout<<"\nname="<<name<<"\nroll="<<roll;

}

};

class B:public A

{float h,w;

public:

void getd()

{ getbase();

cout<<"enter height and weight:";

cin>>h>>w;

}

void showd()

{ showbase();

cout<<"\nheight="<<h<<"\nweight="<<w;

}

};

void main()

{

clrscr();

B b;A a ;

//a.getbase();

b.getbase();

b.getd();

b.showd();

//a.showbase();

getch();

}

Page 111: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

3. How to Access private members of base class in the derived class by using friend class.

Ans.

Accessing private members of base class in the derived class by using friend class

A public member function of a base class can access the private member of the derived

clas irrespective of the friend class has been derived privately or publicly.

Example: A friend class derived privately.

Class base

{ friend class derived;

private:

int count;

base( ):count(0)

{ }

};

class derived : private base

{ public:

void show()

{ cout<<”count=”<<++count; //valid

}

};

void main()

{ derived d1;

d1.show();

getch();

}

Note: if we derive another class from base and try to access the private data member count then

there

will be an error.

class der2:public base

{ public:

void show()

{ cout<<”count=”<<++count; //error , can not access the private data member.

}

};

4)Explain ambiguity in hybrid inheritance.

Ans.

#include<iostream.h>

#include<conio.h>

class base

{

protected:

int a,b;

public:

void get()

{ cout<<"enter a=";

cin>>a;

cout<<"enter b=";

Page 112: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

cin>>b;}

void show()

{ cout<<"a="<<a<<"\nb="<<b;}

};

class d1 : public base

{ protected :int c;

public:

void get1(){cout<<"enter c=";

cin>>c;}

void show1()

{ cout<<"\nc="<<c;

}

};

class d2 : public base

{ protected:int d;

public:

void get2(){cout<<"enter d=";

cin>>d;}

void show2()

{ cout<<"\nd="<<d;

}

};

class child : public d1,public d2

{ int e;

public:

void get3(){cout<<"enter e=";

cin>>e;}

void show3()

{ cout<<"\ne="<<e;

}

};

void main()

{ clrscr();

child c1;

//c1.base::get();

//c1.base::show();

c1.get(); //error member is ambiguous

c1.show(); //error member is ambiguous

//c1.d1::get();

//c1.d2::get();

//c1.d1::show();

//c1.d2::show();

c1.get1();

c1.show1();

c1.get2();

c1.show2();

c1.get3();

c1.show3();

getch();

}

Page 113: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Assignment -5

1. Explain function overriding how it differ from function overloading.

Ans.

Function overriding:

When the same function exists in both the base class and the derived class, the function in the

derived class will be executed. (This is true of objects of the derived class. Objects of the base

class don’t know anything about the derived class and will always use the base class functions.)

We say that the derived class function overrides the base class function. This is called the function

overriding. This overriding is avoided by virtual function to achieve run time polymorphism.

Difference between Overloading and Overriding

No Overloading Overriding

1 Relationship between methods available in

the same class.

Relationship between a super class

method and a subclass method.

2 Does not block inheritance from the super

class.

Blocks inheritance from the super class.

3 Separate methods share (overload) the

same name.

Subclass method replaces (overrides)

the super class method.

4 Different method signatures. Same method signatures.

5 May have different return types. Must have matching return types.

6 May have different declared exceptions. Must have compatible declared

exceptions.

2. Explain memory management operators.

Ans.

Memory management operators :-

Memory management means the way of allocating part of a memory to program at their request,

and freeing it for reuse when no longer needed. In C++ unary operators ‘new’ and ‘delete’ are

used to allocate and free the dynamic memory, they are also called as free store operators.

new:

Pointer variable = new data type;

Here pointers variable is a dynamic variable of type pointer.

The unary operator new is used to allocate required memory at runtime. There are three stages to

allocate required memory they are

c. Locates and reserves storage for the object or objects to be allocated.

d. Initializes the object(s) using class constructor

e. Returns a pointer to the object(s) of a pointer type derived from type-name.

The ‘new’ operator allocates sufficient memory to hold data and return its address. If the object is

of type array it returns the base address of an array. The memory allocated by using new operator

is not initialized. If the required amount of memory is not allocated the operator new throws an

exception to set_new_handler() function. The memory allocated by using new operator

Ex: 1) int *p,*q;

p= new int;

Page 114: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

q= new int;

We can combine the declaration of pointers and their assignments as follows.

2) int *p = new int;

float *x = new float;

Now we can use the above pointers as follows.

*p =15; *x = 18.9;

We can also initialize the memory using the new operator as follows

3) int *p = new int (10);

Thus *p will contain value ‘10’

We can also create one-dimensional array by using new operator as follows.

4) int *p = new int [10];

The above statement creates a memory space for an array of 10 integers hence p[0] will refer

the first element. p[1] to the second element and so on.

3. Write short note on templates.

Ans.

Templates: - A template can be used to create a family of classes or functions. A template can be

considered as a kind of Marco. Template can be defined as class or function parameterized by a

set of type parameters, values, or templates. The type parameters in the template definition are

replaced by specified data type at runtime. The templates are some times called parameterized

classes or functions.

Class templates: -

Class template is a class parameterized by type parameters, values, or templates. To utilize the

class template the template arguments must be passed at the time of instantiation.

The following is the general form of defining class templates.

template <class T>

class name

{

class member specification

with anonymous type T

where ever appropriate.

};

A class created from a class template is called a template class. The syntax of defining an object

of a template class is as follows.

class name <data type> object;

Evaluation Scheme: Component 1* Sessional Test (ST)* 20

Component 2 Assignment Evaluation 10

Component 3** End Term Examination** 70

Total 100

Page 115: OBJECT ORIENTED PROGRAMMING (PCC CS 302)

Assignment

1. Define OOP? Write Down feature of OOPS.

2. Define Advantages of OOPS.

3. Define function and overloading of function.

4. Explain call by value, call by address, call by references with examples.

5. Explain control statements and various type of control statements?

6. Explain input and output in c++ with examples?

7. Explain class and object.

8. Explain member function with an example.

9. Write down friend function with example.

10. Write down friend function overloading with example.

11. Write down constructor and destructor and type of constructor with example.

12. Write down constructor overloading with example.

13. Difference between structure and class?

14. Define static members.

15. Write down binary operator and unary operator overloading with example.

16. Write down Inheritance and types of inheritance with example.

17. Write down polymorphism with example.

18. Write down this pointer with example.

19. Write down virtual function with example.

20. Write down abstract class with example.

21. Write down pointer to object and object to pointer with example.

22. Write down template and type of template with example.

23. Write down exception handling with example.

Page 116: OBJECT ORIENTED PROGRAMMING (PCC CS 302)
Page 117: OBJECT ORIENTED PROGRAMMING (PCC CS 302)
Page 118: OBJECT ORIENTED PROGRAMMING (PCC CS 302)