OOPS Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

Mailam Engineering College, Mailam.

Department of Information Technology


(CS2311/U-I)

UNIT – I

OBJECT ORIENTED CONCEPTS

Syllabus:

Object oriented programming concepts – objects-classes- methods and

messages abstraction and encapsulation-inheritance- abstract classes-

polymorphism. Introduction to C++- objects-classes-constructors and

destructors

PART – A

1. What are the Concepts of OOPs


1. Objects
2. Classes
3. Data Abstraction
4. Data Encapusulation
5. Inheritance
6. Polymorphism
7. Message Passing
8. Dynamic Binding
2. Differentiate Procedure Oriented Programming (POP) and Object
Oriented Programming (OOP)
POP
1) Emphasis on non-real itrem
2) Programs are divided into functions
3) Data are sharable
4) Structured Programming
5) Top-Down Approach
OOP
1) Emphasis on real item
2) Programs are divided into Objects
3) Data are not sharable
4) Object Oriented Programming
5) Bottam-Up Arpproach

Prepared By: Mrs.S.Amutha, AP / IT 1


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

3. Define objects.

Definition1:

―In oop, a problem is considered as a collection of a number of entities called


‗objects‘ objects are instances of classes‖.

Definition2:

―Objects are basic run-time entities in an objected oriented system.


Problem is analyzed in terms of object.

Example: Person, place, table of date etc.

4. Define class.

Definition:

―The entire set of date and code of an objects made as a user-defined


date type with the help of a class ―. C++ enables to define a class that is
similar to struct of C but with addition of functions members. Thus a class
is a collection of similar type‖.

Example: Fruit mango

5. Differentiate between an Object and a Class. [Nov/Dec 2012]


Object
Definition1:
―In oop, a problem is considered as a collection of a number of entities called
‗objects‘ objects are instances of classes‖.
Definition2:
―Objects are basic run-time entities in an objected oriented system.
Problem is analyzed in terms of object.
Example: Person, place, table of date etc.
Class
Definition:
―The entire set of date and code of an objects made as a user-defined
date type with the help of a class ―. C++ enables to define a class that is
similar to struct of C but with addition of functions members. Thus a class
is a collection of similar type‖.
Example: Fruit mango

Prepared By: Mrs.S.Amutha, AP / IT 2


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

6. Define Abstraction and Encapsulation. [May/Jun 2012] [Nov/Dec


2013]
o DATA ABSTRACTION :
―Abstraction refers to the act of representing essential features
without including the background details or explanation. Classes use the
concept of abstraction and are defined as a list of abstraction attributes
such as size, weight and cost and functions to operate on these
attributes‖.

o ENCAPSULATION:
‗The wrapping of data and functions into a single unit (called class)
is known as encapsulation. Data is not accessible to the outside world.

7. Define Object Based Language.


Object Based Language=Encapsulation + Object Identity
Object Oriented Language= Object Based Features + Inheritance +
Polymorphism
8. What is Object Oriented programming? [Nov/Dec 2013]
Definition: ―OOP is a technique where the real world entities are
defined as class hierarchies and we can manipulate them using a
pointer to the root or base class of the hierarchy.‖

OOP = type – extensibility + polymorphism


9. Define const object
We can create constant object by using const keyword before object
declaration.
Example: Const matrix x(m,n);
10. Define tokens.

Definition:

―The smallest individual units in a program are known as tokens .C++ has
following tokens‖:

1. Key words (explicit reserved identifiers)

2. Identifiers (name of variable function)

3. Constants (fixed value do not change)

4. String

5. Operator

Prepared By: Mrs.S.Amutha, AP / IT 3


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

11. What is keyword?

Definition:

This is a list of reserved keywords in C++. Since they are used by the
language, these keywords are not available for re-definition or overloading.
Rules for naming the identifiers in C++.

Example: enum, explicit, export, extern, false, float, for, friend, goto, if

12. What is a scope resolution operator?

Definition:

―The global version of a variable cannot be accessed from within the inner
block in C program. C++ solves this problem by introducing new operator : :
called scope resolution operator.This is used to un cover a hidden variable
and takes the following form

:: variable -name

Example:

Class MyClass

int n1, n2;

public:

void func1(); ---------Function Declaration

};

public void MyClass::func1() ---Use of Scope Resolution Operator to write

Function definition outside class


definition

// Function Code

Prepared By: Mrs.S.Amutha, AP / IT 4


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

13. What do you mean by enumerated data type?

An enumeration is a user-defined type consisting of a set of named


constants called enumerators.

Syntax:

enum [tag] [: type] {enum-list} [declarator]; // for definition of enumerated


type

enum tag declarator; // for declaration of variable of type tag

Example: enum Suit {Diamonds = 5, Hearts, Clubs = 4, Spades };

14. What are symbolic constants?

Symbolic constants are constants represented by symbols. Constants


are values that do not change through out the program execution.

Example:

#include<stdio.h>

#include<conio.h>

#define NUM 15

void main()

int a=NUM;

printf("The constant is %d",a);

getch();

here #define is a preprocessor. Its job is to replace all the entries named
NUM as 15. So that the compiler works with the constant 15...

15. What are the Data Types in C++


 Built-in Data types
 User Defined Data types
 Derived Data Types

Prepared By: Mrs.S.Amutha, AP / IT 5


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

16. Write the Block Structure of C++


Include Files
Class Declaration
Member Function Defintions
Main Function Program
17. What are the Operators in C++
1. Scope Resolution Operator : :
2. Pointer-to-Pointer Member Declarator : :*
3. Pointer-to-Pointer Member Operator ->*
4. Pointer-to-Pointer Member Operator .*
5. Delete-Memory Release Operator
6. Endl-Line feed operator
7. New-Memory allocation operator
8. Setw-Memory width operator
18. What is expression? What are the expressions in C++?
1. Constant Expressions
2. Integral Expressions
3. Float Expressions
4. Pointer Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
19. Define attribute. [May/Jun 2013]
An attribute of an object usually consists of a name and a value; of an
element, a type or class name; of a file, a name and extension
20. What are the Access Specifiers in C++.
1. Public
2. Private
3. Protected
21. What is Static Variables?
Defined with in the function, static variable initialized only once.
Contents of the variables retained throughout the program.
22. What do you mean by dynamic initialization of variables?
C++ permits initialization of the variables at run-time. This is referred
to as dynamic initialization of variables. In C++, a variable can be initialized
at run-time using expressions at the place of declaration as,

Prepared By: Mrs.S.Amutha, AP / IT 6


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

……..
…......
int n =strlen(string);
……..
float area=3.14*rad*rad;
Thus declaration and initialization is done simultaneously at the place where
the variable is used for the first time.
23. What are reference variable?
A reference variable provides an alias(alternative name) for a
previously defined variable. Total, then sum and total can be used
interchancheably to represent that variable.
Syntax:
Data-type &reference-name = variable-name
Example:
float total = 100;
float sum = total;
24. What is the difference between Pointer and a reference? [Nov/Dec
2011]
Pointer :
It is used to store address of other variables
Eg: int *p;
int x;
p=&x;
*p=10;
Reference:
 It provides an alias for previously defined variable
Syntax:
datatype &reference_name = variable_name;

Eg: int count=100;


int &total=count;

 It is used to pass arguments to a function


E.g: void func1(int &a)
{
a=a*10;
}
void main( )
{
int m=10;
func1(m);
}

 Reference variable used as return type

Prepared By: Mrs.S.Amutha, AP / IT 7


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Eg: int &max(int , int); // function call returns a


reference that can be used as a variable

25. What is member-dereferencing operator?


C++ permits to access the class members through pointers. It provides three
pointers-to- member operators for this purpose,
 To declare a pointer to a member of a class. (: :* )
 To access a member using object name and a pointer to the member
(* )
 To access a member using a pointer to the object and a pointer to that
member. ( ->*)
26. What is function prototype?
The function prototype describes function interface to the compiler by
giving details such as number ,type of arguments and type of return values
Function prototype is a declaration statement in the calling program and is
of the following
Type function_name(argument list);
Example: float volume(int x,float y);
27. Static Member Functions?
Static Function can have accessed by only static members declared in
the same class. Static member function called using the name of class
instead of its objects.
28. What is meant by Data Hiding?
Data are hidden inside a class, that can not be accessed by any
function outside the class. It is achieved by declaring the data part as
private.
29. What is function? What are the types of Function in C++?
1. Functions with Arguments and No Return Values
2. Functions with No Arguments and No Return Values
3. Functions with Arguments and Return Values
30. What are the Components of Functions?
1. Function Declaration
2. Function Parameters
3. Function Definition
4. Return Statement
5. Function Call
31. What is a default argument?

Prepared By: Mrs.S.Amutha, AP / IT 8


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Default arguments assign a default value to the parameter, which


does not have matching argument in the function call. Default values are
specified when the function is declared.
Example:
float amount(float principle,int period,float rate=0.15)
Function call is
Value=amount(5000,7);
Here it takes principle=5000& period=7
And default value for rate=0.15
Value=amount(5000,7,0.34)
Passes an explicit value 0f 0.34 to rate
We must add default value from right to left
32. What is Function Overloading?
Overloading refers to the use of same thing for different purpose. i.e.,
same function name performs variety of different tasks. Also known as
Function polymorphism.
33. What is an inline function ?
An inline function is a function that is expanded in line when it is
invoked. That is compiler replaces the function call with the corresponding
function code.
The inline functions are defined as
Inline function- header
{
function body
}
34. Write some situations where inline expansion may not work
 for functions returning values, if loop, a switch, or a goto exists
 for functions not returning values ,if a return statement exists
 if function contain
 if inline
35. What are the Features of Inline Function?
1. Run Faster
2. Function Call & Return is Eliminated
3. Improves Performance
36. What are the parameters passing in C++.
 Pass by value
 Pass by Address

Prepared By: Mrs.S.Amutha, AP / IT 9


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 Pass by reference
37. What is an abstract class in cpp in C++? [Nov/Dec 2012]
Definition:
―A class without any object is known as abstract class. An abstract class is
designed to act as a base class (to be inherited by other classes). It provides
a base upon which other classes may be built‖
38. What is Polymorphism? What are the types of Polymorphism?

Polymorphism means many forms. Types of Polymorphism are

 Runtime Polymorphism

 Compile time Polymorphism

39. What is compile time polymorphism in OOPS? [May/Jun 2013]


It means existence of an entity in various physical forms simultaneously.
Static polymorphism refers to the binding of functions on the basis of their
signature (number, type and sequence of parameters). It is also called early
binding because the calls are type and sequence of parameters). It is also
called early binding because the calls are already bound to the proper type
of functions during the compilation of the program.
40. Define local classes.
Classes can be defined and used inside a function or a block. such
classes are called local classes. It can use global variables and static
variables declared inside the function but cannot use automatic local
variables.
Example:
void test(int a)
{
…….
}
class student
{
………
};
student s1(a);
}
41. Define Constructor.

Prepared By: Mrs.S.Amutha, AP / IT 10


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

It is a member function having name of its class. It is executed


automatically when object is created. It is used to initialize object and
allocate the necessary memory.
42. Define Destructor.
It is a member function having the char ~ followed by name of its
class. It is executed automatically when object goes out of scope. A class
must have only one constructor.
43. Define Constructor Overloading.
A class can have multiple constructors. This is called constructor
overloading.
44. What is order of Constructor and Destructor?
When more than one object is created, they are destroyed in the reverse
Chronological order. Object created must recently is the first one to be
destroyed.
45. Define parameterized constructor
Constructor with arguments is called parameterized constructor
Example:
Class integer
{
int m,n;
public:
integer(int x,int y)
{ m=x;n=y;
}
To invoke parameterized constructor we must pass the initial values as
arguments to the
Constructor functions when an object is declared. This is done in two ways
1. By calling the constructor explicitly
Example:
integer int1=integer(10,10);
2. By calling the constructor implicitly
Example:
Integer int1(10,10);

Prepared By: Mrs.S.Amutha, AP / IT 11


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

46. Define dynamic constructor


Allocation of memory to objects at time of their construction is known as
dynamic constructor. The memory is allocated with the help of the NEW
operator
Example:
Class string
{
char *name;
int length;
public:
string( )
{
length=0;
name=new char[length +1];
}
void main( )
{
string name1(―Louis‖),name3(Lagrange);
}
47. Define copy constructor [Nov/Dec 2011]
A copy constructor is used to declare and initialize an object from
another object. It takes a reference to an object of the same class as an
argument
Example 1: integer i2(i1); would define the object i2 at the same time
initialize it to the values of i1.
Another form of this statement is
Example 2:
integer i2=i1;
The process of initializing through a copy constructor is known as copy
initialization
48. Define multiple constructors (constructor overloading).
The class that has different types of constructor is called multiple
constructors
Example:
#include<iostream.h>
#include<conio.h>
class integer
{

Prepared By: Mrs.S.Amutha, AP / IT 12


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

int m,n;
public:
integer( ) //default constructor
{
m=0;n=0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{m=i.m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}
49. What is the ambiguity between default constructor and default
argument constructor?
The default argument constructor can be called with either one
argument or no arguments. When called with no arguments, it becomes a
default constructor. When both these forms are used in a class, it cause
ambiguity for a statement such as A a; The ambiguity is whether to call
A::A() or A::A(int i=0)
50. Define default argument constructor
The constructor with default arguments are called default argument
constructor
Example:
Complex(float real,float imag=0);
The default value of the argument imag is 0
The statement
complex a(6.0)
assign real=6.0 and imag=0
the statement
complex a(2.3,9.0)

Prepared By: Mrs.S.Amutha, AP / IT 13


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

assign real=2.3 and imag=9.0


51. Differentiate Constructor and Destructors.
Constructors cannot be virtual. Destructors can be Virtual.
Constructors must be declared in public. Destructors must be declared in
public. A constructor has arguments. Destructor has no arguments.
52. Write some special characteristics of constructor
 They should be declared in the public section
 They are invoked automatically when the objects are created
 They do not have return types, not even void and therefore, and they
cannot return values
 They cannot be inherited, though a derived class can call the base
class
 They can have default arguments
 Constructors cannot be virtual function
53. Define default constructor
The constructor with no arguments is called default constructor
Example:
Class integer
{
int m,n;
Public:
Integer( );
…….
};
integer::integer( )//default constructor
{
m=0;n=0;
}
the statement
integer a;
invokes the default constructor
54. When will the destructor be called? is it explicit or implicit.
[May/Jun 2013]
Destructors

Prepared By: Mrs.S.Amutha, AP / IT 14


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

―The function which bears the same name as class itself, preceded by
―tilde ~‖ symbol. The destructor is automatically called with the object
goes out of scope‖.
EXAMPLE: ~ integer().
PART – B
1. Explain about procedure oriented programming in detail.

 Conventional programming using high level languages such as


COBOL, FORTRAN, and C are commonly known as Procedure
oriented Programming
 The problem is viewed as sequence of things to be done such as
reading , calculating, printing
 Functions are used to accomplish the task and primary focus is
on functions.
 The program structure for procedure oriented is shown below,

Main Program

Function 1 Function 2 Function 3

Function 4 Function 5

Function 6
Function 7 Function 8

 Procedure oriented programming consists of writing a list of


instructions ,and organize those instructions into group known
as functions
 Flow charts are used to represent these actions and represent
the flow of control from one action to another.
 Things to be taken in to account in the development of
functions.
 In multi function program , many important data items are
placed a as global , so they can be accessed by all the functions
 Each function may have its own local data

Prepared By: Mrs.S.Amutha, AP / IT 15


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 The relationship of data and functions in procedure oriented


programming can be illustrated as follows

Global data
Global data

Function-1 Function-2 Function-3

Local data Local data Local Data

Draw backs of Procedure oriented programming:

 There is chance of change in global data by functions.


 It is also difficult to identify what data is used by functions in
large programs
 Another problem with procedure oriented approach is the it
doesn‘t provide correct solution to the real world problems
 This is because functions are action oriented , and doesn‘t
correspond to the elements of the problem
Characteristics of Procedure Oriented programming:
 Emphasis on doing things
 Large program are divided into smaller program known as
functions
 Most of the functions share global data
 Data move openly around the system from function to function
 Function transform data from one form to another
 Employs top down approach in program design

2. Difference between structured programming and object oriented


programming
Structured Programming Object oriented programming
Emphasis on algorithm rather Emphasis on data rather than

Prepared By: Mrs.S.Amutha, AP / IT 16


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

than data algorithm


The problem are divided into The problem is divided into
functions objects
Data are declared as global and Data is encapsulated with the
accessible to all functions associated functions and this
without any restrictions capsule is called an object
It has reduced data security and It offers high data security and
integrity since the data is integrity
available to all functions
Programmers faced difficulty in It supports polymorphism which
design , maintenance and reduces software complexity
enhancement of software
It doesn‘t support software It supports inheritance which
reusability provides software reusability
Message passing is possible by Message passing is possible by
means of parameter passing means of communication between
between functions objects
Structured programming Object oriented programming
language has a top down language has a bottom up
approach approach
Some of the structured Some of the object oriented
programming language are C and programming languages are C++
Pascal and Java

3. Explain object-oriented paradigm with all its essential elements.


[Nov/Dec 2005]

 Object oriented approach was invented to remove some of the flaws in


procedural approach.
 OOP treats data as a critical element in the program development.
 Data are not allowed to flow freely around the system.
 It ties data more closely to the function that operate on it and protects
it from accidental modification from outside functions.
 OOP allows decomposition of a problem into a number of entities
called objects.
 The organization in OOP is shown below

Prepared By: Mrs.S.Amutha, AP / IT 17


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Object A Object B

Data Data

Functions Functions

Functions

Data
Object C

 The data of an object can be accessed only by the function associated


with that object.
 However functions of one object can access the functions of other
objects.

Features of Object-Oriented Programming are:


 Emphasis is on data rather than procedure.
 Programs are divided into what are known as objects.
 Data structures are designed such that they are characteristics of
objects
 Functions that operate on the data of an object are tied together in
the data structure.
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program paradigm.

Prepared By: Mrs.S.Amutha, AP / IT 18


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

4. State the application of object oriented methodology. (Nov/Dec


2005)
Application of OOP:
 Real time systems
 Object –oriented databases
 AI and expert system
 Neural network.
 CIM/CAD/CAM system
 Operating System development e.g.: Window NT and Window 2000
 C/S architecture needs middle tier e.g.: DLL written in c++
 N/w programming e.g.: Routers, fire walls

5. Explain the following concepts of object oriented programming in


detail. (Nov/Dec 2006)

Definition: ―OOP is a technique where the real world entities are defined as
class hierarchies and we can manipulate them using a pointer to the root or
base class of the hierarchy.‖

OOP = type – extensibility + polymorphism

Basic concepts of OOP:


The various basic concepts of the oops are.
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

1. OBJECTS:

Definition1:“In oop, a problem is considered as a collection of a number of


entities called ‗objects‘ objects are instances of classes‖.

Definition2: ―Objects are basic run-time entities in an objected oriented


system. Problem is analyzed in terms of object.

Eg: Person, place, table of date etc.

Note:
Objects take up space in the memory and have associated address
like record in Pascal or structure in c.

Prepared By: Mrs.S.Amutha, AP / IT 19


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

EXPLANATION:

 Programming problem must be analyzed in terms of objects and


nature of communication between them.
 Program objects chosen such that they match closely with real world
objects.
 Objects take up space in memory and have associated address like
record in Pascal or structure in c.
 When program executed objects interact by sending message to one
another.
 Objects interact without knowing details of each other date or code.
 It is sufficient to know type of message accepts and type of response
returned by the objects

EXAMPLE: TWO WAYS OF REPRESENTING AN OBJECT

STUDENT
Object: STUDENT
Total
DATA
Name
Date of Birth Average
Marks
………

FUNCTIONS Display
Total
Average
2. CLASSES:
Display
………

2. CLASS:
Definition:
―The entire set of date and code of an objects made as a user-defined
date type with the help of a class ―. C++ enables to define a class that is
similar to struct of C but with addition of functions members. Thus a class
is a collection of similar type‖.

Example: Fruit mango

EXPLANATION:

 Once class defined, we can create any number of objects belonging to


that class

Prepared By: Mrs.S.Amutha, AP / IT 20


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 Each object is associated with data of type class.


 Classes are user-defined data types and behave like built-in-type of a
programming language.

3. DATA ABSTRACTION AND ENCAPSULATION:

 DATA ABSTRACTION :

―Abstraction refers to the act of representing essential features


without including the background details or explanation. Classes use the
concept of abstraction and are defined as a list of abstraction attributes
such as size, weight and cost and functions to operate on these attributes‖.
 DATA HIDING OF INFORMATION HIDING:
―The Insulation of data from direct access by the program is called
‗data hiding or information hiding‖

 ENCAPSULATION:
‗The wrapping of data and functions into a single unit (called class) is
known as encapsulation. Data is not accessible to the outside world.

EXPLANATION:
 Only functions wrapped in the class can access it.
 Functions provide interface between objects data and program.
 ABSTRACT DATA TYPE:

―Classes use the concept of data abstraction known as abstract data


type (ie) acts of representing essential features without including the
background details or explanations.

4. INTERITANCE: [Provides idea of Reusability]

Definition1:
―Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports concept of hierarchical
classifications‖.

Definition2:
―It is a mechanism of extending an existing class into a new class. The
new class will have all the attributes to the old class plus some of its own.
The new class is said to the inherited or derived from old class.

EXPLANATION:

 Provides the idea of reusability


 Add additional features to an existing class without modifying it.
 Possible to derive new class from existing one.

Prepared By: Mrs.S.Amutha, AP / IT 21


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 New classes have combined features of both the classes.


 Real power of inheritance mechanism is allow programmer to reuse a
class without any undesirable side-effects into rest of classes.
Property Inheritance

Bird
Attributes
Feathers
Lay Eggs

Flying Bird Non Flying Bird


Attributes Attributes
………… …………
………… …………

Robin Swallow Penguin Kiwi


Attributes Attributes Attributes Attributes
………… ………… ………… …………
………… ………… ………… …………

5. POLYMORPHISM:

Definition1: ―The ability of an object to behave differently in different context


given the same message.‖

Definition2:―Polymorphism means one name, multiple forms. It allows us to


have more than one function with same name in a program.‖

EXPLANATION:
 Operation exhibit different behaviors in different instances.
 Extensively used in implementing inheritance.
 Supports operator over loading ,function over loading
Example: Particular word with severed different meanings depending on
context

Prepared By: Mrs.S.Amutha, AP / IT 22


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Example: POLYMORPHISM

Shape

Draw( )

Circle object Box Object Triangle object

Draw (Circle) Draw (box) Draw (Triangle)

 OPERATOR OVER LOADING :


“Process of making an operator to exhibit different behaviors in
different instance‖

 FUNCTION OVER LOADING :


―Single function name perform different type of tasks‖

6. DYNAMIC BINDING/LATE BINDING:


Definition:
―Dynamic binding or late binding means code associated with a given
producer call is not known until the time of the call at run-time. It is
associated with polymorphism and inheritance.

EXPLANATION:
 Binding refers to the linking of a procedure call to be executed in
response to the call.
 At run-time, the code matching object under current reference will be
called.

7. METHODS AND MESSAGE PASSING:

 Object orient program consists of set of objects that communicate


with each other with following steps:
1. Create classes that define object &behaviors
2. Create object from class define and
3. Establishing communicate among objects

Example:
employee. Salary (name);

Prepared By: Mrs.S.Amutha, AP / IT 23


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

employee.salary(name);

Object message information

6. Describe the advantages of OOP. (8) [May/June 2007]

 Inheritance concept eliminate redundant code and extent use of


existing classes
 Date hiding build secure programs
 Message passing techniques make interface description with external
system simpler.
 Software complexity easily managed.
 Easy to partition the work in project based on objects.
 Object oriented structures are easily upgraded from small to large
system.
 OOP supports saving of development time and higher productivity.
 C++ programs are easily maintainable and expandable.
7. Difference between C and C++.

C C++
It is a kind of structure oriented It is an object oriented programming
programming language language

It has bottom up approach


It has top-down approach
It give importance to data
It gives importance to Algorithm

Data has global visibility and it


The movement of data is restricted.
moves freely around the system. So
So that , accidental modification is
that it can be modified accidently
not possible
anywhere within the program
Hiding the information from external Information can be hidden and it is
interference is not possible not available to external world
It supports reusability
It doesn‘t support reusability

It doesn‘t support polymorphism It supports polymorphism which

Prepared By: Mrs.S.Amutha, AP / IT 24


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

reduces software complexity


The return type of main ( ) by default
is int. By default it is void

C doesn‘t require to provide a return


type , It is mandatory in C++
to main( )
printf( ) and scanf( ) functions are cin and cout objects are used for IO
used in IO operations operations
C programs have extension c
C++ program have extension cpp

8. Justify the need for object- oriented paradigm. [April/May 2008]


 Co-operation among different objects helps to exchange of messages.
 Information hiding and data abstraction increase reliability.
 Dynamic binding increase flexibility of addition of new class of
objects.
 Inheritance helps reusability of codes to increase productivity
 Standard class library in OOP Language saves lot of coding and
debugging effort
9. Write in detail about identifiers and Constants
Identifiers:
 Identifiers refer to the names of variables , functions,
arrays, classes etc; created by the programmers
 They are the fundamental requirement of any language
Rules for naming identifiers :
 An identifier cannot be a keyword.
 Alphabets, digits and underscore are permitted .
 The name cannot start with a digit.
 Both uppercase and lower case letters are permitted but
they are treated differently.
 There is no limit for identifier length.
Example: stud_name, REGNO, regno
Constants:
 Constants refer to fixed value that does not change
during execution of a program.
 Different types of literal constants are integer, character,
floating point, and string constants.

Prepared By: Mrs.S.Amutha, AP / IT 25


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 Literal constants do not have memory location


Example: 123 // integer constant
13.3 // floating constant
―C++‖ // String constant
Keywords:
ANSI C++ has all the ANSI C and earlier versions of c++ keywords.
These reserved words may not be used as constant or variable or any other
identifier names.

asm else new this


auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

10. What are the different data types supported by C++? [April/May
2008]
 Data types in C++ can be classified under various categories as shown
in the below figure

Prepared By: Mrs.S.Amutha, AP / IT 26


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

C++ Data Types

Derived
User Defined
Type Built-in Type Type
Structure Array
Union Function
Class Pointer
Enumeration Reference

Integral Type Void Floating


Type

int char float double

 C and C++ compiler supports all the built-in data types


 The basic data types may have several modifiers like signed,
unsigned, long and short.
 Data type representation is machine specific in C++.
 All combinations of the basic types and modifiers along with their size
and range for a 16-bit machine is shown.

SIZE AND RANGE OF C++ BASIC DATA TYPES

TYPE BYTES RANGE


Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 -128 to 127
Int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 32768 to 32767
Short int 2 32768 to 32767
unsigned Short int 2 0 to 65535
signed Short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
Signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295

Prepared By: Mrs.S.Amutha, AP / IT 27


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

float 4 3.4E-38 to 3.4E+38


double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Two Uses of void are:
 To specify the return type of a function when it is not returning
any value.
 To indicate an empty argument list to a function
Eg : void funct(void);

Basic data types

C++ supports integer (int), real (float and double) and character
(char) basic data types.
int
 The int data type is used for signed integer values.
 The data type can be modified with the unsigned
modifier for use with unsigned values.
float
 The float data type is used for 32 bit floating point
values.
double
 The double data type is used for 64 bit double precision
floating point values.
char
 The char data type is a one byte value.
 This data type can also be modified with the unsigned
modifier for use with unsigned byte values.

void :
 It is a null or empty data type.
 It is a functions does not return any values .
 void data type is used as return type to return null
values
E.g: void getdata( ); // function with no return value
void putdata(void); // function that takes no arguments
void *p; // creates general purpose data type
User defined data type:
Some of the user defined data types in C++ are Structure, Union, and
Enumerated
Structure:
It is collection of variables which can be of different types

Prepared By: Mrs.S.Amutha, AP / IT 28


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Syntax:
struct struct-type-name{
type name1: length;
type name2: length;
.
.
type nameN : length;
}variable_list;

Eg: struct student


{
char stud_name[30];
int regno;
};
Union:
It is similar to structure but memory usage is less than struct

Syntax:

union union-type-name{
type member-name;
type member-name;

}union-variables;

E.g: union stud


{
char stud_name[30];
int regno;
};

Enumeration:
enum is a keyword which automatically enumerates a list of
words by assigning values 0,1,2,3…
Syntax:
enum enum_name{list of names}var list;
Eg:
enum Boolean {TRUE,FALSE}
enum dyas{Sunday… Saturday}
enum color{Red=1,Blue, Green=5, Orange}
Derived data types:
Some of the derived data types are Arrays, Function and pointer
Arrays:
It is used to represent the similar data type
Eg: int a[10];
char name[20];
Function:
Self contained program structure that performs a specific task

Eg: int add( int x, inty)

Prepared By: Mrs.S.Amutha, AP / IT 29


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

{
int z;
z=x+y;
return z;
}

Pointer :
It is used to store address of other variables
Eg: int *p;
int x;
p=&x;
*p=10;
Constant Pointer:
 Constant pointer is the one that cannot point to
anything other than what it is pointing to at the time of
its definition
 Value assigned to it doesn‘t change throughout the
program
 Value stored in the constant pointer is address of
another variable
 Address itself cannot be changes but however the
content of that address can be changed
Eg:
int value=10;
int *const p= &value; // constant pointer
*p=100; //allowed , contents can be
changed
p++; //not allowed , pointer
address itself can‘t be changed
Pointer to constant:
It is a pointer variable that can point any memory
location, but the content of the memory location to
which it points cannot be modified.
Eg:
int value=10;
int const*p=&value;
*p=100; // invalid, content at the memory
location cannot be changed

Reference:
 It provides an alias for previously defined variable

Prepared By: Mrs.S.Amutha, AP / IT 30


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Syntax:
datatype &reference_name = variable_name;

Eg: int count=100;


int &total=count;

 It is used to pass arguments to a function


E.g: void func1(int &a)
{
a=a*10;
}
void main( )
{
int m=10;
func1(m);
}

 Reference variable used as return type


Eg: int &max(int , int); // function call returns a
reference that can be used
as a variable

Variables:
 Variables are used to store different values
 In C++, variable can be declared anywhere in the
program before its first usage
 Variable must be declared and it must be initialized
before it is used.
Declaration of variables:

Syntax: datatype variable_name;

Eg: int a;
char c;
Initialization of variable:
The variable can be assigned in two ways either in
normal initialization or in dynamic initialization
Normal Initialization:
 The normal initialization is also called as compile
time initialization.
 Value of the variable is known to the compiler at
the time of compilation
Eg:
int a= 10;

Prepared By: Mrs.S.Amutha, AP / IT 31


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Dynamic initialization:
 It is also called as run time initialization
 Values of the variable is assigned at the time of
execution
Eg:
int a, b;
cin>>a;
cin>>b;
int c;
c=a*b;
cout<<c;
11. What are the operators available in C++? Explain in detail about it.
All the C++ operators work in an identical manner as in C. Some of
the old operators have new meaning in C++.Some of the new operators
introduced in C++ is listed below:
Operator Meaning
:: Scope resolution operator , it is used to indicate a
member of a specified class
::* A member pointer operator
* Pointer to member using object. I t is used to
indicate a pointer to a member of a specified class
->* Pointer to member using pointer to object operator
Delete Memory release operator
New Memory allocation operator
reinterpret_cast Casting operator which is used to cast from any type
to any other type
const_cast Removing the const nature of a variable while
casting
dynamic_cast casting operator that can be used to safeguard
against irrelevant casting
Typeid Used to find type of an object at run time. Useful for
handling exceptions
Throw useful for throwing an exception at the time of an
error

Scope resolution operator


 Scope resolution operator is used to uncover the hidden
variables.
 It also allows access to global version of variables

Eg:
#include<iostream. h>
int m=10; // global variable m
void main ( )
{
int m=20; // local variable m
cout<<‖m=‖<<m<<‖\n‖;
cout<<‖: : m=‖<<: : m<<‖\n‖;
}
output:

Prepared By: Mrs.S.Amutha, AP / IT 32


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

20
10 (: : m access global m)
Scope resolution operator is used to define the function outside the class.
Syntax:
return type <class name> : : <function name>

Eg:

void x : : getdata( )

new and delete operators:


 In C malloc( ) and free( ) are functions for allocating and deallocating
memory ,In C++ new and delete operators performs this action.
 New and Delete operators are called as free store operators since they
allocate the memory dynamically.
 New operator can be used to create objects of any data type.

Pointer-variable = new data type;

 Initialization of the memory using new operator can be done. This can
be done as,

Pointer-variable = new data-type(value)

 Delete operator is used to release the memory space for reuse. The
general form of its use is

Delete pointer-variable;

Placement new operator:


The normal new can be used as follows
int*p= new int; // normal new call
int *p = new (nothrow)int; // which does not throw exception in
case if memory not allocated and return
the pointer value as null
int*p=(int*)new int[3][4]; // for allocating memory for arrays
int*p=new int(3) // for initializing the variable at the time of
memory allocation
The ―Placement new ― operator is one form of new operator , it works
as follows,
int*p=new int; // normal new
int *q=new(p) int; //placement new
In this example no memory is allocated for the q variable here, its
address is same as p.

Prepared By: Mrs.S.Amutha, AP / IT 33


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Significance of delete operator:


 If the new variables are not deleted , the memory space occupied by
new variables will continue to increase while the program is running
 At some point memory will be exhausted and the program will crash.
 If machine shuts down all space occupied is released automatically
and there is no memory crunch problem

New Casting operator‟s typeid and throw:


 C++ has a new function like casting as well as old C style casting. For
example to convert the integer variable to float
In C it can be written as

FloatVar=(float)IntVar;

In C++ it can be written as

FloatVar=float(IntVar);

 For better typecasting dynamic_cast, reinterpret_cast,


dynamic_cast,static_cast and const_cast are added in ANSI C++.
 These operators as well as typeid are used in Real Time Type
Identification (RTTI).
 Operator throw is used when exception handling is used to trap
errors in C++
12. What are the difference and advantages of new operator over malloc
new malloc( )
new is an operator.
malloc ( ) is a function
Syntax of new is simpler than malloc(
) It has complex syntax

No size, no void, and no casting are


It is need to specify the size of the
required for the new operator.
memory to be allocated
new operator can be used in malloc( ) can be used only in
allocating memory for arrays, allocation in memory
initializing the variable at the time of
memory allocation.
Operators execute faster than
Function executes slower than
functions
operators
Possibility of implementing an
operator as function in c++. Functions are not used as operators

The new operator is class-aware,


that is the meaning of new can be
The malloc( ) function can be
changed to suit the need of user
overloaded .
define class and this is known as
operator overloading

Prepared By: Mrs.S.Amutha, AP / IT 34


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

13. Explain how function can be overloaded in different ways.

Function Overloading:
o When a function redefined with different set of arguments, then
it is known as overloaded function. This process is known as
function overloading
o Function overloading means we can use the same function
name to create functions that perform a variety of different
tasks.
o For example define a function Add(int,int), this function can be
redefined as Add(float,float),this function is now overloaded
function
o In first case the function Add( )is used to add two integer
values, in the second case, the same function is used to add
two float values.
o The function Add( ) performs different tasks depends upon the
value passed to it.
Rules to overload a function:
o To overload any function, the function should have an
argument
o The overloaded function should differ only on arguments
o During the overloading, the basic meaning of the overloaded
function should not be allowed to change. That is the Add( )
function should not be used for performing arithmetic
operations other than addition.
o The return type of the function can be similar or different type.
Types of function overloading:
A function is overloaded in the following ways
o Function overloading based on different argument types
o Function overloading based on different number of arguments
o Function overloading based on different sequence of
arguments
o Function overloading based on different argument types
Program for Function Overloading With Different Types Of Arguments

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

Prepared By: Mrs.S.Amutha, AP / IT 35


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

using namespace std;


void Display(int); //arguments type is int
void Display(double); //argument type is double
void Display(char); //argument type is char
void main( )
{
Display(10); //integer value is passed
Display(2.56); //double value is passed
Display(‗c‘); //character value is passed

}
void Display(int x) //defined to display an integer value
{
cout<<x<<‖\t‖;
}
void Display(double d) //defined to display a double value
{
cout<<d<<‖\t‖;
}
void Display(char a) //defined to display a character value
{
cout<<a<<‖\t‖;
}

Sample output:
10 2.56 c

Explanation:
o In this program, the function Display( ) is first defined to
display an integer value .The same function is redefined to
display a double value, and a character value.
o Here the same function behaves differently when called with
integer value, double value and character value.
o The compiler automatically calls the correct version of the
function based upon the type of data used as an arguments
o The character value must be placed with single quotes during
function call.

Function overloading based on different number of arguments:

 Here the function to be overloaded uses different number of


arguments. The program illustrates this concept
#include<iostream.h>
#include<conio.h>
using namespace std;
void Display(int); //one argument

Prepared By: Mrs.S.Amutha, AP / IT 36


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void Display(int,int); //two arguments


void Display(int,int,int); // three arguments
void main( )
{
Display(10);
Display(10,20);
Display(10,20,30);
}
void Display(int x) //defined to display one integer value
{
cout<<‖x:‖<<x<<‖\n‖;
}
void Display(int x, int y) //redefined to display two integer value
{
cout<<‖x:‖<<x<<‖y:‖<<y<<‖\n‖;
}
void Display(int x, int y , int z) //redefined to display three integer value
{
cout<<‖x:‖<<x<<‖y:‖<<y<<‖z:‖<<z<<‖\n‖;
}

Sample output:
x:10
x:10y:20
x:10y:20z:30

Explanation:
 The function here differs based on the number of arguments
rather than the type of arguments.
 The function Display( ) is defined to display one integer value.
the same function is redefined to display two and three integer
values respectively
 The compiler calls the correct version of the function based
upon the number of data used as arguments
 The number of argument may be same or different type.
Function overloading based on different sequence of arguments:
 The function to be overloaded uses different sequence of arguments,
the following program illustrates this,
#include<iostream.h>
#include<conio.h>
using namespace std;
void Display(int,double); //first argument is int, second is double
void Display(double,int); //first argument is double .second is int
void main( )
{
Display(10,12.5); //sequence is int and double
Display(12.5,10); //sequence is double and int
}

Prepared By: Mrs.S.Amutha, AP / IT 37


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void Display(int I , double d) //defined to display one integer value


{
cout<<i<‖\t‖<<d<<‖\n‖;
}
void Display(double d , int i) //redefined to display two integer value
{
cout<<d<<‖\t‖<<i;
}
Sample output:
10 12.5
12.5 10

Explanation:
 The function Display ( ) is declared and defined to the different
sequence of arguments.
 In the first call, the order of value passed to the function is integer
and double value whereas in the second call the order of passing
value is double and integer.
 The compiler calls the correct version of the function based upon the
sequence of data used as an argument

Default argument Vs Function overloading


Differences:
 The default argument is simpler than the function overloading ,since
we do not need to write two different versions of the function
 In case of default arguments, when the user does not specify the
argument, default value is implicitly passed.
 In case of function overloading , only explicitly specified arguments
are passed

Similarity:
The function calls in both cases do not differ.

14. Write in detail about Friend fucntion


Friend functions:
 Friend functions are special functions. The class grants these
functions a special privilege to access private and protected variables
of the class.
 Even though it is declared inside the class definition, it is not
considered as member of a class.
 A friend function begins with the keyword friend

Prepared By: Mrs.S.Amutha, AP / IT 38


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

General form of friend function

friend return_type function_name(argument list)


{
statement ;
}

 Friend function can be friends with more than one class


 It is possible to call the friend function using an object name and a
class member access operator(dot or arrow).
 Instead friend functions are called like regular functions
 Friend function arguments should be an object of the class for which
it is friend.
 Friend function is not inherited
Program to illustrate the friend function:

#include<iostream.h>
#include<conio.h>
using namespace std;
class sample
{
private:
int a,b;
public:
sample(int x , int y)
{
a=x;
b=y;
}
friend int max(sample); //friend function declaration ,object
is used as an argument
};
int Max(sample s) //friend function defined like a
regular function
{
if(s.a>s.b) //the access of private data
members
return s.a;
else
return s.b;
}
void main( )
{
sample s1(100,50);
int m = Max(s1); //friend function called like a
regular function
cout<<‖Max:‖<<m;
}

Prepared By: Mrs.S.Amutha, AP / IT 39


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Sample output:
Max:100

Program for friend function can be friend with more than one class.
#include<iostream.h>
#include<conio.h>
using namespace std;
class two; //forward declaration
class one
{
private:
int x;
public:
one(int a) //constructor function
{
x=a;
}
friend int Max(one,two); //friend function declaration

};
class two
{
private:
int y;
public:
two(int b) //constructor function
{
y=b;
}

friend int Max(one,two);//friend function declaration


};
int Max(one o ,two t)
{
if(o.x>t.y) //the access of private data members
return o.x;
else
return t.y;
}
void main( )
{
one o(100);
two t(50);
int m= Max(o,t); //calling friend function ,objects are passed
cout<<‖Max:‖<<m;
}

Sample Output:
Max:100

Explanation:

Prepared By: Mrs.S.Amutha, AP / IT 40


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

o The function Max( ) is declared as friend function and it is


friend to classes one and two respectively
o It is necessary to have forward declaration of class two since it
is used in the class one definition.
Uses of friend function:
o Friend function are useful with operator overloading
o Friend function is best choice when you want a non-member
function to have access to the private member of a class
o These functions are designed to provide generic utilities. Such
function are needed when more than one class would like to
share the same utility
Drawbacks:
o Having a friend function actually is violation of information
hiding principle of object oriented programming since a friend
function can access the private member of a class

Friend Class:
o In addition to declaring individual friend functions, it is
possible to have an entire class to be friend to other classes
o This can be useful if a class is used with another class that all
the methods in that class need access to the private members
of the other class
o The trust is one directional that is ,if class1 defined class 2 to
be its friend, the class2 member functions can access private
variables of class1 but the class1 member function cannot
access private variables of the class2

Program to illustrate the friend class:

#include<iostream.h>
#include<conio.h>
using namespace std;
class two; //forward declaration
class one
{
private:
int x;
public:
one(int a) //constructor function
{
x=a;
}

Prepared By: Mrs.S.Amutha, AP / IT 41


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

friend two ; //class two members can access private parts of


class one

};
class two
{
private:
int y;
public:
two(int b) //constructor function
{
y=b;
}

int Max(one); //member function declaration


};
int two:Max(one o )
{
if(o.x>y) //member function of class two access the private
member of one
return o.x;
else
return y;
}
void main( )
{
one o(100);
two t(50);
int m= Max(o,t); //calling friend function ,objects are passed
cout<<‖Max:‖<<mt.Max(o);
}

Sample Output:
Max:100
15. Explain the concept of pointers with an example program written in
c++. [April/May 2010]
 Pointers offer a unique approach to handle data in C and C++.
 Pointer is a derived data type that refers to another data variable by
storing the variable‘s memory address rather than data.
 A pointer variable defines where to get the value of a specific data
variable instead of defining actual data.

Declaring and initializing pointers


The declaration of a pointer variable takes the following form:
Syntax:
data-type * pointer-variable;
Example:
int *Ptr;

Prepared By: Mrs.S.Amutha, AP / IT 42


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 Ptr is a pointer variable and points to integer data type.


 Ptr should contain the memory location of any integer variable.
 Initialization of a pointer variable is done as follows:
int *Ptr,a; //declaration
ptr=&a; // initialization
ptr-contains the address of the variable ‗a‘.

&-address of operator.
*-used to retrieve the address of a variable.

Void Pointer
 It is also known as generic poimter, which refer to variables of any
data type.
 Before using void pointers, we must type cast the variables to the
specific data types that they point to.

Manipulation of Pointers
 Indirection operator (*) or deference operator is used to access the
pointer variable content.

Syntax
* pointer_variable;
PROGRAM
//Manipulation of pointers
# include <iostream.h>
#include<conio.h>
void main
{
int a=10,*Ptr;
Ptr=&a;
cout<<‖The value of a is:‖<<a<<endl;
*Ptr=(*Ptr)/2;
cout<<‖The value of a is :‖<<(*Ptr) ;<<endl;
}

OUTPUT
The value of a is: 10
The value of a is: 5

Pointer Expressions and pointer Arithmetic


 A pointer can be incremented (++) or decremented (- -)
 Any integer can be added to a subtracted from a pointer.
 One pointer can be subtracted from other.
//Arithmetic Operations on Pointers
# include<iostream.h>
# include<conio.h>
void main( )

Prepared By: Mrs.S.Amutha, AP / IT 43


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

{
int num [ ]={10,20,30,40,50};
int *Ptr;
int i;
cout<<‖The array values are:\n‖;
for(i=0;i<5;i++)
cout<<num[i]<<‖\n‖;
\\ initializing the base address of Str to Ptr */
Ptr=num;
/*Printing the value in the array*/
cout<<‖\n value of Ptr:‖<<*Ptr;
cout<<‖\n‖;
Ptr++;
cout<<‖\n value of Ptr++:‖<<*Ptr;
cout<<‖\n‖;
Ptr--;
cout<<‖\n value of Ptr--:‖<<*Ptr;
cout<<‖\n‖;

Ptr=Ptr-1;
cout<<‖\n value of Ptr-1:‖<<*Ptr;
cout<<‖\n‖;
Ptr + = 3;
cout<<‖\n value of Ptr + = 3:‖<<*Ptr;
Ptr - = 2;
cout<<‖\n‖;
cout<<‖\n value of Ptr - = 2:‖<<*Ptr;
cout<<‖\n‖;
getch( );
}

OUTPUT
The array values are
10
20
30
40
50
Value of Ptr : 10
Value of Ptr ++ : 20
Value of Ptr-- : 10
Value of Ptr+2 : 30
Value of Ptr-1 : 20
Value of Ptr+3 : 50
Value of Ptr-=2 : 30
16. What are the advantages of using default arguments? Explain with
an example program.
DEFAULT ARGUMENTS:
Definition:
―C++ allows us to assign default values to the function parameters,
when the function is declared. In such case we can call a function without

Prepared By: Mrs.S.Amutha, AP / IT 44


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

specifying all its arguments .Used in situation where some arguments have
some value‖.
Example: bank interest.
float amount(float principal,int period, float rate=0.15);
Note:
―The compiler looks at the prototype to see how many arguments a function
uses and alerts the program for possible default values‖.

ADVANTAGES:
 Default argument add new parameter to existing function
 Used to combine similar function into one

PROGRAM:
#include<iostream.h> // header part
#include<conio.h>

int vol(int=1,int=2,int=3); // Function declaration

int main()
{
clrscr();

int length; // Variable declaration


int width;
int height;
int volume;

cout<<"\n Enter the value of length = ";


cin>>length;

cout<<"\n Enter the value of width = ";


cin>>width;

cout<<"\n Enter the value of heigth = ";


cin>>height;

Prepared By: Mrs.S.Amutha, AP / IT 45


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

volume=vol(); // Access Function


cout<<"\n Volume with no argument passed = "<<volume<<endl;

volume=vol(length);
cout<<"\n Volume with one argument passed = "<<volume<<endl;

volume=vol(length,width);
cout<<"\n Volume with two argument passed = "<<volume<<endl;

volume=vol(length,width,height);
cout<<"\n Volume with all argument passed = "<<volume<<endl;

getch();
return 0;
}
17. Write a program to demonstrate how a static data is accessed by a
static member function.
STATIC MEMBER FUNCTIONS:
Definition:
―A function which precedes the static keyword before the definition. It
can only access the static members of the class. Though static member
functions are defined like member functions, they are not truly members.
SYNTAX:
class_name :: function_name;
static void disptotal();
PROPERTIES OF STATIC MEMBER FUNCTION:
 A static function can have access to only other static members
declared in the same class.
 A static member function can be called using the class name

PROGRAM:
//Static member variables and functions
class test
{
int code;
static int count; // static variable
public:

Prepared By: Mrs.S.Amutha, AP / IT 46


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<<‖Object Number:‖<<code<<‖\n‖;
}
static void showcount(void) // static member function
{
cout<<‖count:‖<<count<<‖\n‖;
}
};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); // Accessing static member function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}

Note: static member variable and static member function can be accessed
within class but cannot using object.

18. What is an inline function? Explain the situations where inline


expansion may not work? [Nov/Dec 2011]

INLINE FUNCTIONS:
Definition:

Prepared By: Mrs.S.Amutha, AP / IT 47


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

‗This is the function which, when a statement calling them is


compiled is replaced by the body of the same function‘. All inline function
must be defined before they are called with the keyword inline to the
function definition‖.
Syntax:
inline function_header
{
function body
}

Example:
inline double cube (double a)
{
return (a*a*a);
}

 ADVANTAGE OF INLINE FUNCTION:


 Inline functions are far superior than macros.
 Eliminate cost of calls to small function
 Makes program run faster
 SITUATION WHERE INLINE EXPRESSION NOT WORK:
 For functions returning values , if a loop , switch or goto exists.
 For functions not returning values, if a return statements exists.
 If function, contain static variable.
 If inline function are recursive.
Program:

#include<iostream>
using namespace std;
inline float mul( float x , float y)
{
return (x*y)
}
inline double div (double p , double q)
{
return (p/q)
}
int main()
{

float a= 12.34;
float b= 9.8;
cout<< mul (a,b)<<‖\n‖;
cout<< div (a,b)<<‖\n‖;
return 0;
}

Prepared By: Mrs.S.Amutha, AP / IT 48


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

19. Describe Abstract base class. Illustrate an example to explain it.


Abstract class
A class without any object is called abstract class. An abstract class has
atleast one pure virtual member function. Instances of an abstract class
cannot be created.

class File //abstract class


{
public:
int virtual open( )=0; //pure virtual
int virtual close( )=0; //pure virtual
};

EXPLANATION:
Abstract classes are usually outcome of generalization process which
finds out common elements of the classes and stores them in a base class.
20. Define polymorphism. Describe the type of polymorphism with
example. [May/Jun 2013]
Polymorphism
―Polymorphism is the property of the same object to behave differently in
different contexts given the same message‖
Two types of polymorphism
1. Compile time polymorphism
2. Run time polymorphism

Polymorphism

Runtime
Compile Time

Function Operator Virtual


Overloading Overloading Functions

Prepared By: Mrs.S.Amutha, AP / IT 49


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Overview
 Introduction (Compile Time polymorphism and Runtime
Polymorphism)
 Pointer object
 This pointer
 Compatibility of derived and base class pointers
 Virtual Functions
 Static vs Dynamic Binding
1. Introduction
Compile Time Polymorphism
Achieved by function overloading and operator overloading
Function overloading:
A single function name can be used for various purposes (with
different arguments)
Operator overloading:
Single operator is used to achieve multiple operations (with different
type of operands)
Runtime polymorphism
 Run time polymorphism is achieved by virtual functions.
 Resolving function call at run time is known as runtime or late or
dynamic binding.
 Runtime polymorphism allows selecting the suitable function at run
time.
2. Pointer object
 Pointer object is a variable containing an address of an object which is
similar to pointer variable.
 Use & operator to get the address of an object.
Advantages
 Pointer object is used to achieve a run time polymorphism.
 It is a polymorphic object to access member functions of different
classes.
3. This Pointer
Definition
The name ―this‖ is a keyword. The pointer this allows to access the current
object only.‘ This‘ pointer is used within a method to access an object
member. It is also used to return the address of the current object.

Prepared By: Mrs.S.Amutha, AP / IT 50


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Program
#include<iostream>
#include<conio>
using namespace std;
class A
{
private:
int x;
public:
A( ) {}
A(int a)
{
this->x=a; //accessing data member
}
A disp( )
{
return *this; //returns the address of an object
}
};
void main( )
{
A(10);
A a1,a2;
a2=a1.Disp( );
}
4. Compatibility of derived and base class pointers
#include <iostream>
using namespace std;
class Base
{
public:
virtual void runme() { cerr << "Base" << endl; }
};

class Derived : public Base


{
public:
virtual void runme() { cerr << "Derived" << endl; }

Prepared By: Mrs.S.Amutha, AP / IT 51


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

};

int main()
{
Base *p = new Derived; // get rid of parens
p->runme();
return 0;
}

5. Virtual Functions
Definition:
“A function defined with virtual keyword in the base class is known
as virtual function. Compiler will decide the exact class pointed to, by the
base class pointer and call the respective function of that class if the
function is defined as virtual‖.

Virtual table:
―A table consisting of pointers to all virtual functions of class, every
class with atleast one virtual function will have one copy of virtual table‖.

Virtual Destructors
The issue of more unreferenced memory blocks is solved by virtual
destructors.
Syntax
class shape
{
public:
virtual ~shape( ){………} //virtual destructors
};
Rules for virtual function:
 Functions name must be proceeded by virtual keyword in the base
class.
 Virtual constructors are not possible. Constructing a derived class
object needs specific construction of the base class sub object
within.
 The function in the derived class must have same name as of the
virtual function defined in the base class and the same prototype.

Prepared By: Mrs.S.Amutha, AP / IT 52


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 The function in the derived class need not be preceded by the


virtual keyword.
 The virtual function must be defined in the base class, it may have
an empty body.
 The virtual functions are members of the classes of the hierarchy.
Program
//Virtual Functions.cpp

#include<iostream.h>
#include<conio.h>
using namespace std;
class Shape
{
public:
virtual void Draw()
{
cout<<"\n Shape is drawn:";
}
};

class Circle: public shape


{
public:
void Draw( )
{
cout<<"\n Circle is drawn:";
}
};
void main()
{
Shape *ptr,s;
Circle c;

ptrs=&s;
ptrs->Draw( ); //calling base class draw
function

ptrs=&c;
ptrs->Draw( ); //calling derived class draw
function

Output:

Shape is drawn

Circle is drawn

Prepared By: Mrs.S.Amutha, AP / IT 53


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

6. Static vs Dynamic Binding


Static Binding Dynamic Binding
Static binding is dynamic binding refers
method resolution at to method resolution
compile time at run time

20. What is meant by a constructor? State the various characteristics


of constructor with an example. [Nov/Dec 2009]
[Nov/Dec 2013]

 Constructors:
―A constructor is a special member function whose task is to initialize the
objects of its class. It is special because its name is same as class name.
The constructor of a class is the first member function to be executed
automatically when an object of the class is created”.

 Constructor has two main functions


1. It automatically initializes the object.(i.e constructor function need to
be called explicitly, it is automatically called when the object is
defined).
2. It usually provides initial values for the data members of the object.

Syntax:
Class classname
{
Public:
Classname( ); //constructor prototype
}
Classname :: classname( )
{
//constructor body definition
}

Example:
class integer
{
int m,n;
public:
integer(void); // constructor invoked
………
………
};
integer: :integer(void) //constructor defined
{
m=0,n=0;
}

Prepared By: Mrs.S.Amutha, AP / IT 54


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 Similar to other members the constructor can be defined either


within or outside the body of a class. It can access any data
member like all other member functions but cannot be invoked
explicitly and must have public status to serve its purpose.
 The constructor which does not take arguments explicitly is
called default constructor.

A constructor has the following characteristics:


 It has the same name as that of the class to which it belongs.
 It is executed automatically whenever the class is instantiated.
 It does not have any return type.
 It is normally used to initialize the data members of a class.
 An object with a const cannot be used as a member of a union.
 It is also used to allocate resources such as memory to the
dynamic data members of a class.
 They make implicit calls to the operators new and delete when
memory allocation is read.
 It should have public access within the class.
 It cannot be declared as static or const.
 Constructor cannot be virtual.
 They cannot be inherited, though a derived class can call the
base class constructor.
PROGRAM:
// Simple constructor.cpp
#include <iostream>
using namespace std;
class stack
{
private:
int stack pointer;
int stack array[10];
public:
stack()
{
stack pointer=0; // Automatic initialize sp;
}

Prepared By: Mrs.S.Amutha, AP / IT 55


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void push (int values)


{
if (stack pointer==9)
{
cout<<"stack overflow! can't insert!";
}
else
{
stack array[stack pointer]=value;
stack pointer ++;
}
}
int pop()
{
if (stack pointer==0)
cout<<"stack underflow,cannot pop";
else
{
stack pointer--;
return stack array{stack pointer];
}
}
};
void main()
{
stack mystack;
// * mystack.initize sp(); /This is automatically done.We do not need to
do it explicitly now/
mystack.push(1);
mystack.push(2);
cout<<mystack.pop()<<"\n";
cout<<mystack.pop()<<"\n";
}

Prepared By: Mrs.S.Amutha, AP / IT 56


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

21. What is the need of object initialization? State the various rules for
defining constructor. [May/Jun 2013]
 Need For Object Initialization

 When object declared, we need to initialize individual data


members to specific default values.
 Integer variables to zero and pointer variables to null are two
common initializations.
 Example: In stack object definition, initializing stack pointer to
null using a constructor.
 Dynamic Memory Allocation required when object defined.
 Example: Billing a customer (ie) better to provide memory
enough for items using constructor.
 Object need to set special values. Constructors define objects
and give them special values.
 Example: When new student defined, provide his name, address
and other attributes with it.
 In inheritance, a base class with constructor allows derived class
to have one to initialize itself
 Rules for defining constructors:
 A constructor must have the same name as the class itself.
 To have more than one constructor we should have a single
constructor and overload it with different set of arguments.
 A constructor cannot specify a return type. Even writing void is
not allowed
 A constructor should not have a return statement in the body of
the constructor itself.
 An address of a constructor cannot be obtained.
 We can define constructors as private, but that would disable us
from defining objects using those constructors. Therefore, unless
normal definition of the object is not restricted, the constructors
should be defined public.
22. State the need of copy constructor. Explain copy constructor with
suitable C++ coding. [May/June 2007]
 Need for copy constructor:

Prepared By: Mrs.S.Amutha, AP / IT 57


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

 We can pass all type of arguments to constructors except the


object itself.
 However we can pass the reference of the native object to the
constructor, which is a pointer to same type of object.
 This type of constructor is known as copy constructor.
 Copy constructor:
Definition: ―When one object is copied to another using initialization
they are copied by executing copy constructor". Thus a copy
constructor is used to declare and initialize an object from another
object".
Example: integer I2(I1);
or
integer I2=I1;
PROGRAM:
#include<iostream>
using namespace std;
class code
{
int id;
public:
code( ) { } //constructor
code(int a) {id=a}
code(code &x)
{
id=x.id;
}
void display(void)
{
Cout<<id;
}
};
int main( )
{
code A(100); //object A is created and initialized
code B(A); //copy constructor is called

Prepared By: Mrs.S.Amutha, AP / IT 58


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

code C=A; // copy constructor called again


code D; //D is created, not initialized
D=A; //copy constructor not called
cout<<‖\n id of A: ―; A. display ( );
cout<<‖\n id of B: ―; B. display ( );
cout<<‖\n id of C: ―; C. display ( );
cout<<‖\n id of D: ―; D. display ( );

return 0;
}
OUTPUT
id of A : 100
id of B : 100
id of C : 100.
id of D : 100

23. Explain constructor with default arguments using suitable C++


coding
Definition “A constructor without any argument is called default
constructor‖
1. Compiler Defined Default Constructor:
―The constructor which is provided by the compiler when the user has not
defined any. It may not be physically synthesized by the compiler‖.
2. User Defined Default Constructor:
"The default constructors synthesized by the compiler cannot do all the
initializations that we need for our class. The synthesized constructor fulfills
only the requirement of the compiler. So it the programmer/user
responsibility to do initialization explicitly. Such types are called 'user
defined default constructor'.
PROGRAM:
//DefArgs Cons.cpp
#include<iostream>
using namespace std;
class time
{

Prepared By: Mrs.S.Amutha, AP / IT 59


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

public:
int Hours;
int Minutes;
int Seconds;
void ShowTime( )
{
cout<<‖Time is ―<<Hours<<‖Hours : ―<<Minutes<<‖Minutes: and
―<<Seconds<<‖Seconds \n‖;
}
Time ( ) { }
Time (int TempHours, int TempMinutes=0, int TempSeconds=0)
{
Hours=TempHours;
Minutes=TempMinutes;
Seconds=TempSeconds;
}
};
void main ( )
{
Time Time1 (12, 15, 15);
cout<<‖The Time Number 1 \n‖;
Time1.showtime ( );
Time Time2 (10, 30);
cout<<‖The Time Number 2 \n‖;
Time2.showtime ( );
Time Time3;
Time3 = Time (12);
cout<<‖The Time Number 3 \n‖;
Time3.showtime ( );
Time Time4 = 12;
cout<<‖The Time Number 4 \n‖;
Time4.showtime ( );
}

Prepared By: Mrs.S.Amutha, AP / IT 60


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

24. Explain parameterized constructor using suitable C++ coding.


Definition ―A constructor with one or more than one argument is called
parameterized constructors."
Example:
Class integer
{
int m,n;
public:
integer(int x, int y); // parameterized constructor
...........
..........
};
integer::integer(int x,int y)
{
m=x;n=y;
}

Note:
In object declaration we must pass initial values as arguments to the
constructor function either in the following two ways:
 By calling the constructor explicitly.
 By calling the constructor implicitly.

 EXPLICIT CALL
Example: integer int1=integer (0,100);
 IMPLICIT CALL
Example: integer int1 (0,100);

PROGRAM:
#include <iostream>
using namespace std;
class integer
{
int m,n;
public:

Prepared By: Mrs.S.Amutha, AP / IT 61


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

integer(int,int);

void display(void)
{
cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";
}
};
integer::integer (int x, int y) // constructor defined
{
m=x, n=y;
}
int main()
{
integer int1(0,100); // constructor called implicitly
integer int2=integer(25,75); //constructor called explicitly
cout<<"\n OBJECT1"<<"\n";
int1.display();
cout<<"\nOBJECT2"<<"\n";
int2.display();
return 0;
}
Output:
OBJECT1
m=0
n=100
OBJECT2
m=25
n=75
25. Explain constructor with dynamic allocation using suitable C++
coding.
Definition ―Constructor uses new to allocate memory for objects at the time
of creation which is common to only when the objects are of varied size and
the size is available only at run time." Such constructors are referred as
constructor with dynamic allocation."

Prepared By: Mrs.S.Amutha, AP / IT 62


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Note
 Object initialization can be done either at the compile time or at run
time.
 Also we can reinitialize an object created at compile time or
 We can create an object and initialize it at runtime.
PROGRAM
//DynamicMem Alloc.cpp
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name=new char[length+1];
}
string(char*s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display(void)
{

cout<<name<<"\n";
}
void join(string &a,string &b);
};
void string::join(string &a,string&b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void main()
{
clrscr();
string name1("object");
string name2("oriented");
string name3("programming lab");
string s1,s2;

Prepared By: Mrs.S.Amutha, AP / IT 63


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();

s1.display();
s2.display();
getch();
}

26. Explain destructor using suitable C++ coding. . [Nov/Dec 2013]

 Destructors―The function which bears the same name as class itself,


preceded by ―tilde ~‖ symbol. The destructor is automatically called with
the object goes out of scope‖.
EXAMPLE: ~ integer().
Implementation of destructor:
PROGRAM:
#include<iostream>
using namespace std;
int count=0;
class alpha
{
public:
alpha ( )
{
count++;
cout<<‖\n no of object created‖<<count;
}
~alpha ( )
{
cout<<”\n no of object destroyed”<<count;
count--;
}
};
int main( )
{
cout<<‖\n Enter Main\n‖;
Alpha A1,A2,A3,A4;
}
cout<<‖\n Enter Block1\n‖;
Alpha A5;
}
{
cout<<‖\n Enter Block2\n‖;
alpha 6;
}

Prepared By: Mrs.S.Amutha, AP / IT 64


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

cout<<‖\n Re-Enter Main \n‖;


return 0;
}

OUTPUT
Enter Main
No of objects created 1
No of objects created 2
No of objects created 3
No of objects created 4

Enter Block 1
No of objects created 5
No of objects destroyed 5

Enter Block 2
No of objects created 5
No of objects destroyed 5

Re-Enter Main
No of Objects destroyed 4
No of Objects destroyed 3
No of Objects destroyed 2
No of Objects destroyed 1

27. Write a C++ program that will ask for a temperature in Fahrenheit
and display it
ALGORITHM:
Step 1: Start the program
Step 2: the program should prompt the user to enter the temperature value
to convert.
Step 3: Finally, display the converted value.
Step 4: Depending on the choice, use the following formulas.
Step 5: Formula to convert from Celsius to Fahrenheit: ((9/5)*degC)+32.
Step 6: Formula to convert from Fahrenheit to Celsius: 5*(degF-32)/9
Step 7: The process must continue until the user enters the option to quit
the program.
Step 8: You must create two separate functions for the temperature
conversion.
Step 9: one for the Celsius-to-Fahrenheit conversion and another one for the
Fahrenheit-to-Celsius conversion.
Step 10: end of the program.

Prepared By: Mrs.S.Amutha, AP / IT 65


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

PROGRAM:
#include <iostream>
using namespace std;
int main()
{
int ftemp;
int ctemp;
int select = 0;
cout << "Please select from the following: " << endl;
cout << "1) Fahrenheit-to-Celsius" << endl;
cout << "2) Celsius-to-Fahrenheit" << endl << endl;
cout << "Enter: ";
cin >> select;
if (select == 1)
{
cout << " Enter temperature in Fahrenheit to convert to degrees Celsius: ";
cin >> ftemp;
ctemp = (ftemp-32) * 5 / 9;
cout << "Equivalent in Celsius is: " << ctemp << endl;
}
else if (select == 2)
{
cout <<" Enter temperature in Celsius to convert to degrees Fahrenheit: ";
cin >> ctemp;
ftemp = ctemp*9/5 + 32;
cout << "Equivalent in Fahrenheit is: " << ftemp << endl;
}
else
cout << "Valid options 1 or 2." << endl;
return 0;
}
28. Write a C++ program that inputs two numbers and output the
largest number using Class. [ Nov/Dec 2009]

ALGORITHM:
Step 1: Start the program
Step 2: define a class as large

Prepared By: Mrs.S.Amutha, AP / IT 66


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

Step 3: define function show within class large


Step 4: define function show to print the largest of two numbers
Step 5: within the main function create object for class large
Step 6: access the function show through object
PROGRAM
# include <iostream.h>
class large
{
int x,y;
public:
void read( )
{
cin>>x>>y;
}
void display( )
{
cout<<x<<y;
}
void largest( )
{
if(x>y)
cout<<‖x is largest‖;
else
cout<<‖y is largest‖;
}
};
void main ( )
{
larget l;
l.read( );
l.diaplay( );
l. largest( );
}

29. Write a C++ program to multiply two matrices and print the result.
[April/May 2010]
# include<iostream.h>
main ( )
{
int a [3] [3], b [3] [3], c [3] [3], i,j,k;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
{
Cin>>a[i][j];
Cin>>b[i][j];
}
for (k=0;k<3;k++)
{
for(i=0;i<3;i++)
{

Prepared By: Mrs.S.Amutha, AP / IT 67


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

for(j=0;j<3;j++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for (i=0;i<3;i++)
for (j=0;j<3;j++)
cout<<c[i][j];
}

30. Write a complete C++ program to do the following:


a. „Student‟ is a base class, having two data members:
entryno and name; entryno is integer and name of 20
characters long. the value if entryno is 1 for Science
student and 2 for Arts student, otherwise it is an error.
b. „Science‟ and „Arts‟ are two derived classes, having
respectively data items marks for physics, chemistry,
Mathematics and marks for English, History, Economics.
c. Read appropriate data from the screen for 3 science and 2
arts students.
d. Display entryno, name, marks for science students first
and then for arts students. [May/Jun 2013]

#include<iostream.h>

#include<conio.h>

class student

char name[20];

int enum entryno={―science‖,‖Arts‖};

int no;

public:

void insert()

cout<<‖Enter the Student Name,entry type‖<<endl;

cin>>name>>no;

Prepared By: Mrs.S.Amutha, AP / IT 68


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void display()

cout<<‖\n\n\n*-*-*-*-* Student Details *-*-*-*-*‖<<endl;

cout<<‖\nName:—>‖<<name<<endl

<<‖\nEntryno:—>‖<<no<<endl;

};

class science:public student

int m1,m2,m3;

public:

void get()

insert();

cout<<‖Enter the 3 subject marks‖<<endl;

cin>>m1>>m2>>m3;

void put()

display();

int total;

total=m1+m2+m3;

cout<<‖\n\n\tMarks1:‖<<m1<<endl

<<‖\n\tMarks2:‖<<m2<<endl

<<‖\n\tMarks3:‖<<m3<<endl

Prepared By: Mrs.S.Amutha, AP / IT 69


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

<<‖\t————‖<<endl

<<‖\tTotal :‖<<total<<endl;

};

class Arts: public student

public:

char sports_grade[20]; //data member

};

class awards:public exam,sports

public:

void input()

put();

cout<<‖\n\nGrades to Match‖<<endl

<<‖*-*-*-*-*-*-*-*-*‖<<endl

<<‖ \nA Grade – 200 to 300 ―<<endl

<<‖ \nB Grade – 100 to 199 ―<<endl

<<‖ \nC Grade – 0 to 99 ―<<endl;

};

void main()

awards obj;

Prepared By: Mrs.S.Amutha, AP / IT 70


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

clrscr();

obj.get();

obj.input();

getch();

31. Illustrate the concept of function overloading to find the area of


circle and square.
ALGORITHM:
Step 1: Start the program
Step 2: declare and define two function name area.
Step 3: define first area function to calculate area of circle
Step 4: define second area function to calculate area of square
Step 5: both function name should be same but argument differ
Step 6: call both function by passing value
Step 7: end of the program.

PROGRAM:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;

double Area(double radius); //prototype for area of circle


double Area(double length, double width); //prototype for area of square

const double PI(3.142);

int main()
{

double radius(0.0);
cout << endl << "Enter radius: ";

Prepared By: Mrs.S.Amutha, AP / IT 71


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

cin >> radius;

double length(0.0);
cout << "Enter length: ";
cin >> length;
double width(0.0);
cout << "Enter width: ";
cin >> width;
cout << endl << "Area of circle is: " << setprecision(5) << Area(radius)
<< endl << "Area of square is: " << setprecision(5) << Area(length, width)
<< endl;
system("PAUSE");
return 0;
}

double Area(double radius)


{
return (PI*radius*radius);
}

double Area(double length, double width)


{
return (length * width);
}
32. i)Write a C++ program that inputs two numbers and outputs the
largest number using class.
ALGORITHM:
Step 1: Start the program
Step 2: define a class as Big
Step 3: define function show within class big
Step 4: define function show to print the largest of two numbers
Step 5: within the main function create object for class Big
Step 6: access the function show through object
Step 7: end of the program.

PROGRAM:

Prepared By: Mrs.S.Amutha, AP / IT 72


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

class Big
{
private:
int a;
int b;
public:
void show()
{
cout<<"enter the a and b value";
cin<<a<<b;
if(a>b)
cout<<"a is largest";
else
cout<<"b is largest";
}
};
void main()
{
Big n;
n.show();
}
ii) Write a C++ program that takes either two integers or two floating
point numbers and outputs the smallest using class friend function and
function overloading
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the class name as Base with data members and member
functions.
STEP 3: The function get() is used to read the 2 inputs from the user.
STEP 4: Declare the friend function mean(base ob) inside the class.
STEP 5: Outside the class to define the friend function and do the following.
STEP 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
STEP 7: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base

Prepared By: Mrs.S.Amutha, AP / IT 73


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
33. Illustrate the concept of function overloading to find the Maximum
of two numbers. [Nov/Dec 2011]
#include<iostream.h>
#include<conio.h>
class over
{
public:
int get(int,int);
float get(float,float);
};
int over::get(int a,int b)

Prepared By: Mrs.S.Amutha, AP / IT 74


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

{
if(a>b)
return a;
else
return b;

}
float over::get(float a,float b)
{
if(a>b)
return a;
else
return b;
}
void main()
{
int n1,n2,t;
float x,y,temp;
over obj;
clrscr();
cout<<‖\nEnter two integer number: ―;
cin>>n1>>n2;
t=obj.get(n1,n2);
cout<<‖Maximum number is: ―<<t;
cout<<‖\nEnter two float number: ―;
cin>>x>>y;
temp=obj.get(x,y);
cout<<‖Maximum number is: ―<<temp;
getch();
}
34. Write a C++ program to define overload constructor to perform
string initialization, string copy and string destructions. [May/Jun
2012]

Prepared By: Mrs.S.Amutha, AP / IT 75


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50

class string
{
char str[MAX];
public:
friend void operator>>(istream &din,string &s1)
{
din>>s1.str;
}

friend void operator<<(ostream &dout,string &s1)


{
dout<<s1.str;
}

void operator+=(string s1);


void operator==(string s1);
void operator=(string s1);
void operator~();
void operator!();
void operator^(string s1);

string()
{
strcpy(str,‖ ―);
}

string(char s[])
{
strcpy(str,s);
}
};

void string::operator+=(string s1)


{
if(strlen(str)+strlen(s1.str)<MAX)
{
strcat(str,s1.str);
cout<<‖\n\nConcatinated string is: ―<<str;
}
else
{
cout<<‖\n\nSorry the array size is exceeded.‖;

}
}

Prepared By: Mrs.S.Amutha, AP / IT 76


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

void string::operator==(string s1)


{
if(strcmp(str,s1.str)==0)
cout<<‖\n\nStrings are equal.‖;
else
cout<<‖\n\nStrings are not equal.‖;
}

void string::operator=(string s1)


{
strcpy(str,s1.str);
cout<<‖\n\nCopy of string is: ―<<str;
}

void string::operator~()
{
strrev(str);
cout<<‖\n\nReverse of string is: ―<<str;
}

void string::operator!()
{
string temp;
strcpy(temp.str,str);
strrev(str);
if(strcmp(temp.str,str))
cout<<‖\n\nString is not palindrome.‖;
else
cout<<‖\n\nString is palindrome.‖;
}

void string::operator^(string s1)


{
if(strstr(str,s1.str))
cout<<‖\n\n‖<<s1.str<<‖ is substring of ―<<str<<‖.‖;
else
cout<<‖\n\nSubstring is not present.‖;
}

void main()
{
string s1,s2;
int choice;
char ans;
clrscr();
cout<<‖\n\n **** STRING OPERATIONS ****‖;
do
{
cout<<‖\n\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
‖;
cout<<‖\n\n MENU:‖;
cout<<‖\n\n\t1.Concatination of string\n\n\t2.Equality\n\n\t3.Copy

Prepared By: Mrs.S.Amutha, AP / IT 77


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

string\n\n\t4.Reverse of string\n\n\t5.Palindrome\n\n\t6.Occurance of
substring‖;
cout<<‖\n\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
‖;
cout<<‖\n\nEnter your choice: ―;
cin>>choice;
switch(choice)
{

case 1:
cout<<‖\n\nEnter the first string: ―;
cin>>s1;
cout<<‖\n\nEnter the second string: ―;
cin>>s2;
s1+=s2;
break;

case 2:
cout<<‖\n\nEnter the first string: ―;
cin>>s1;
cout<<‖\n\nEnter the second string: ―;
cin>>s2;
s1==s2;
break;

case 3:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
s2=s1;
break;

case 4:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
~s1;
break;

case 5:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
!s1;
break;

case 6:
cout<<‖\n\nEnter the string: ―;
cin>>s1;
cout<<‖\n\nEnter the string which you want to check for occurance: ―;
cin>>s2;
s1^s2;
break;

Prepared By: Mrs.S.Amutha, AP / IT 78


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

default:
cout<<‖\n\nPlease enter correct choice.‖;
break;
}
cout<<‖\n\n\nDo you want to continue?(y/n): ―;
flushall();
cin>>ans;

}while(ans==‘y‘ || ans==‘Y');
getch();
}

35. Write a C++ program to Generate Fibonacci using Copy Constructor.


[Nov/Dec 2012]

#include <iostream.h>
class fibonacci
{
private:
unsigned long int f0,f1,fib,
public:
fibonacci()
{
f0=0;
f1=1;
fib=f0+f1;
}
fibonacci (fibonacci &ptr)
{
f0=ptr.f0;
f1=ptr.f1;
fib=ptr.fib;
}
void increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
}
void display()
{
cout << fib << 't\';
}
}; //end of class construction
void main (void)
{
fibonacci number;
for (int i=0; i<=15;i++)
{
number.display();
number.increment();

Prepared By: Mrs.S.Amutha, AP / IT 79


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

}
}
36. Write a C++ program to implement Dynamic memory allocation.
[Nov/Dec 2012]
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name=new char[length+1];
}
string(char*s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display(void)
{

cout<<name<<"\n";
}
void join(string &a,string &b);
};
void string::join(string &a,string&b)
{
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void main()
{
clrscr();
string name1("object");
string name2("oriented");
string name3("programming lab");
string s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
s1.display();
s2.display();

Prepared By: Mrs.S.Amutha, AP / IT 80


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

getch();
}

ANNA UNIVERSITY QUESTIONS


PART – A

1. What is the difference between Pointer and a reference? [Nov/Dec


2011]
Refer Q-No: 24

2. What are copy constructors? [Nov/Dec 2011]


Refer Q-No: 47

3. Define Abstraction and Encapsulation. [May/Jun 2012] [Nov/Dec


2013]
Refer Q-No: 6

4. When will the destructor be called? is it explicit or implicit.


[May/Jun 2013]
Refer Q-No: 54

5. Differentiate between an Object and a Class. [Nov/Dec 2012]


Refer Q-No: 5

6. What is an abstract class in cpp in C++? [Nov/Dec 2012]


Refer Q-No: 37

7. Define attribute. [May/Jun 2013]


Refer Q-No: 19

8. What is compile time polymorphism in OOPS? [May/Jun 2013]


Refer Q-No: 39

9. What is object oriented programming? [Nov/Dec 2013]


Refer Q-No: 8

Prepared By: Mrs.S.Amutha, AP / IT 81


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

PART – B

1. Explain the basic concepts of OOPS. [Nov/Dec 2011]


Refer Q-No: 5

2. Write a C++ program that will ask for temperature in Fahrenheit


and display it. [Nov/Dec 2011]
Refer Q-No: 27

3. Illustrate the concept of function overloading to find the


Maximum of two numbers. [Nov/Dec 2011]
Refer Q-No: 33

4. What are Inline functions? Write sample to explain it. [Nov/Dec


2011]
Refer Q-No: 18

5. Explain in detail about class, object, methods and messages.


[May/Jun 2012]
Refer Q-No: 5

6. Write a C++ program to define overload constructor to perform


string initialization, string copy and string destructions.
[May/Jun 2012]
Refer Q-No: 34

7. Explain the characteristics of OOPS in detail. [Nov/Dec 2012]


Refer Q-No: 1

8. Write a C++ program to Generate Fibonacci using Copy


Constructor. [Nov/Dec 2012]
Refer Q-No: 35

9. What is polymorphism? Explain different types of polymorphism.


[Nov/Dec 2012]
Refer-Q-No: 20

10. Write a C++ program to implement Dynamic memory


allocation. [Nov/Dec 2012]
Refer-Q-No: 36

11. Define polymorphism. Describe the type of polymorphism


with example. [May/Jun 2013]
Refer-Q-No: 20

Prepared By: Mrs.S.Amutha, AP / IT 82


Mr.P.Mathivanan, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-I)

12. Explain the order in which constructors are called when an


object of a derived class is created. [May/Jun 2013]
Refer-Q-No: 21

13. Write a complete C++ program to do the following:


a. „Student‟ is a base class, having two data members:
entryno and name; entryno is integer and name of 20
characters long. the value if entryno is 1 for Science
student and 2 for Arts student, otherwise it is an error.
b. „Science‟ and „Arts‟ are two derived classes, having
respectively data items marks for physics, chemistry,
Mathematics and marks for English, History, Economics.
c. Read appropriate data from the screen for 3 science and 2
arts students.
d. Display entryno, name, marks for science students first
and then for arts students. [May/Jun 2013]
Refer-Q-No: 30

14. Write a C++ program to list out prime numbers between the
given two limits. [Nov/Dec 2013]
Refer Q-No:

15. What are constructors? Explain the concept of destructor with


an example. [Nov/Dec 2013]
Refer Q-No:20 & 26

16 . (i)List out the features of object oriented programming.


(iii) Distinguish between abstraction and encapsulation
(iii) Explain Do-While with an example. [Nov/Dec 2013]

Refer Q-No: 1& 2 & 3 & 5

Prepared By: Mrs.S.Amutha, AP / IT 83


Mr.P.Mathivanan, AP/IT

You might also like