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

OBJECT-ORIENTED PROGRAMMING SYSTEM –ASSIGNMENT NO-1

(SOLUTIONS)
1. List the benefits and applications of object oriented programming. Differentiate between a structure
and a class.
Solution- benefits of object oriented programming- pg no:-12
applications of object oriented programming – pg no:-14
Differences
S.No Concepts
Class Struct
1 Re-usability Completely re-usable Not re-usable
The data of an Object of a Struct
All the functions of a Class are visible to its
2 Visibility is not visible to other objects of
objects
the same Struct
Pass by
Reference &
3 Uses Pass by Reference Uses Pass by Value
pass by
Value
The functions of a class can be inherited by its
4 Inheritance Never allows inheritance
subclasses; allows inheritance
Default All the members of a Class are private by All the members of a Struct are
5
Visibility default public by default
Size When The size of the empty Struct is 0
6 The size of an empty Class is 1 Byte
Empty Bytes
Garbage As it uses pass by reference, garbage As it uses pass by value, garbage
7
Collection collection is possible collection is not possible
The lack of garbage collection
Memory The ease of the garbage collection process
8 results in poor memory
Management helps in effective memory management
management
Allows constructors of all types, such as with Only allows parameterized
9 Constructors
or without parameters constructors
10 Destructors Can use it Cannot use it
Member
Allows direct initialization of member Does not allow direct word
11 Variables
variables initialization of member variables
Initialization
Object It is a must to use the keyword ‘new’ during It is optional to use the keyword
12
Creation object creation ‘new’ during object creation
Better for smaller and simpler
When to Better for larger and complex objects where
13 objects where inheritance is of
Use? inheritance is required
less importance.
2. What are the principles of object oriented programming? Explain.
Solution :- pg no- 7-12

3. What is object oriented programming ? How is it different from procedure oriented programming?
Solution:- Object-oriented programming is the successor of procedural (structural)
programming. Procedural programming describes programs as groups of reusable code units
(procedures) which define input and output parameters. Procedural programs consist of procedures,
which invoke each other.

The problem with procedural programming is that code reusability is hard and limited – only
procedures can be reused and it is hard to make them generic and flexible. There is no easy way to work
with abstract data structures with different implementations.
The object-oriented approach relies on the paradigm that each and every program works with data that
describes entities(objects or events) from real life. For example: accounting software systems work with
invoices, items, warehouses, availabilities, sale orders, etc.
This is how objects came to be. They describe characteristics (properties) and behavior (methods) of
such real life entities.

BASIS FOR
POP OOP
COMPARISON

Basic Procedure/Structure Object oriented.


oriented .

Approach Top-down. Bottom-up.

Basis Main focus is on Main focus is on 'data security'.


"how to get the Hence, only objects are permitted
task done" i.e. on to access the entities of a class.
the procedure or
structure of a
program .

Division Large program is Entire program is divided into


divided into units objects.
called functions.

Entity accessing mode No access specifier Access specifier are "public",


observed. "private", "protected".

Overloading/Polymorphism Neither it overload It overloads functions,


functions nor constructors, and operators.
operators.

Inheritance Their is no provision Inheritance achieved in three


of inheritance. modes public private and
protected.
BASIS FOR
POP OOP
COMPARISON

Data hiding & security There is no proper Data is hidden in three modes
way of hiding the public, private, and protected.
data, so data is hence data security increases.
insecure

Data sharing Global data is Data is shared among the objects


shared among the through the member functions.
functions in the
program.

Friend functions/classes No concept of friend Classes or function can become a


function. friend of another class with the
keyword "friend".
Note: "friend" keyword is used only
in c++

Virtual classes/ function No concept of Concept of virtual function appear


virtual classes . during inheritance.

Example C, VB, FORTRAN, C++, JAVA, VB.NET, C#.NET.


Pascal

4. Distinguish between the following terms with reference to object oriented programming.
Solution:- i)Early binding and late binding
BASIS FOR
EARLY BINDING LATE BINDING
COMPARISON

Event Occurrence Events occur at compile time Events occur at run time are
are "Static Binding". "Dynamic Binding".

Information All information needed to All information need to call


call a function is known at a function come to know at
compile time. run time.

Advantage Efficiency. Flexibility.

Time Fast execution. Slow execution.

Alternate name Static Binding. Dynamic Binding.

Example overloaded function call, Virtual function in C++,


overloaded operators. overridden methods in java.
ii) Inheritance and polymorphism
BASIS FOR
INHERITANCE POLYMORPHISM
COMPARISON

Basic Inheritance is creating a Polymorphism is basically a common


new class using the interface for multiple form.
properties of the already
existing class.

Implementation Inheritance is basically Polymorphism is basically


implemented on classes. implemented on function/methods.

Use To support the concept of Allows object to decide which form of


reusability in OOP and the function to be invoked when, at
reduces the length of compile time(overloading) as well as
code. run time(overriding).

Forms Inheritance may be a Polymorphism may be a compile


single inheritance, time polymorphism (overloading) or
multiple inheritance, run-time polymorphism (overriding).
multilevel inheritance,
hierarchical inheritance
and hybrid inheritance.

Example The class 'table' can The class 'study_table' can also have
inherit the feature of the function 'set_color()' and a class
class 'furniture', as a 'Dining_table' can also have function
'table' is a 'furniture'. 'set_color()' so, which form of the
set_color() function to invoke can be
decided at both, compile time and
run time.

iii) Objects and classes


BASIS FOR
OBJECT CLASS
COMPARISON

Definition An instance of a class A template or blueprint with which


is known as Object. objects are created is known as
Class.

Type of entity Physical Logical

Creation Object is invoked by Class is declared by using class


new keyword. keyword.

Memory allocation Creation of object The formation of a class doesn't


consumes memory. allocate memory.
iv)Dynamic binding and message passing
Dynamic binding is a method of linking a procedure call with its code. This binding gets done only when
the code is executed. The code is not known until runtime. Because of this, dynamic binding is also
called late binding.

Message passing is a method of exchanging messages or developing communication between objects.


Objects send and receive messages between themselves just like humans do. For message passing, the
name of the objects between messages will be passed must be specified, along with the information to
be shared and the name of the function.

5. Differentiate between operator and function overloading with the help of suitable example.
Solution:-
C++ allows you to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a previously
declared declaration in the same scope, except that both declarations have different arguments and
obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate
definition to use by comparing the argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the most appropriate overloaded
function or operator is called overload resolution.

Function Overloading
If any class have multiple functions with same names but different parameters then they are said to be
overloaded. Function overloading allows you to use the same name for different functions, to perform,
either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to perform
one single operation but with different number or types of arguments, then you can simply overload the
function.
You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the number of arguments
in the argument list. You cannot overload function declarations that differ only by return type.Where
same function display() is being used to print different data types.

Operators Overloading
Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator
is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on
user-defined data type. For example '+' operator can be overloaded to perform addition on various data
types, like for Integer, String(concatenation) etc.
Types of Operator
 Uri nary operator
 Binary operator
Example

6. Explain the various data-types, control structures and tokens present in c++.
Solution:- Data Types:- pg no-38-43
Control structures:- pg no:-64-69
Tokens:- pg no:-36

7. What are reference variables?


Solution:- pg no:- 47-49
8. Explain with examples two ways how the member functions of a class are defined in C++.
Solution:- pg no:-103-104

9. Find the output of the following program

Solution:- Program goes in infinite loop and prints 1 infinitely.

10. write a c++ program to find if a number is prime using inline and macro function.
Solution:- PRIME as inline function
PRIME as macro

11. Write a C++ program to find maximum of two numbers using inline function.
12. With suitable example explain the following :
i) Call by reference
ii) Return by reference
iii) Call by value
Solution:-i) Call by reference -pg no:-81-82

ii) Return by reference-pg no-82


iii)Call by value – pg-79-80

13. With the help of suitable example explain function overloading.


Solution:- pg no:-87-89
14. How do the following statements differ?
char *const p;
char const * p;
Solution:- The qualifier const can be applied to the declaration of any variable to specify that its value
will not be changed. const keyword applies to whatever is immediately to its left. If there is nothing to
its left, it applies to whatever is immediately to its right.

const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr,
but you can change the pointer itself. “const char *” is a (non-const) pointer to a const char.

NOTE: There is no difference between const char *p and char const *p as both are pointer to a const
char and position of ‘*'(asterik) is also same.

char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p,
but can change the value pointed by ptr.

// C program to illustrate
// char* const p
#include<stdio.h>
#include<stdlib.h>

int main()
{
char a ='A', b ='B';
char *const ptr = &a;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n\n", ptr);

//ptr = &b; illegal statement (assignment of read-only variable ptr)

// changing the value at the address ptr is pointing to


*ptr = b;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n", ptr);
}

Output:

Value pointed to by ptr: A


Address ptr is pointing to: -1443150762

Value pointed to by ptr: B


Address ptr is pointing to: -1443150762

NOTE: Pointer always points to same address, only the value at the location is changed.

const char * const ptr : This is a constant pointer to constant character. You can neither change the
value pointed by ptr nor the pointer ptr.

// C program to illustrate
//const char * const ptr
#include<stdio.h>
#include<stdlib.h>

int main()
{
char a ='A', b ='B';
const char *const ptr = &a;

printf( "Value pointed to by ptr: %c\n", *ptr);


printf( "Address ptr is pointing to: %d\n\n", ptr);

// ptr = &b; illegal statement (assignment of read-only variable ptr)


// *ptr = b; illegal statement (assignment of read-only location *ptr)

Output:

Value pointed to by ptr: A


Address ptr is pointing to: -255095482

NOTE: char const* *const ptr is same as const char *const ptr.

15. An electricity board charges the following rates to domestic uses to discourage large consumption of
energy:
For the first 100 units: 60P per unit
For the next 200 units: 80P per unit
Beyond 300 units: 90P per unit
All users are charged a minimum of Rs. 50.00. If the total amount is more than Rs. 300.00, then an
additional surcharge of 15% is added.
Write a C++ class program to read the names of users and number of units consumed and print out
the changes with names.
Solution:-
16. Identify the error in the following program:
#include<iostream.h>
Class Space
{
int mCount;
Public:
Space()
{
mCount=0;
}

Space Operator ++()


{
mCount++;
return Space (mCount);
}
};

void main()
{ Space ObjSpace;
ObjSpace++;
}
Solution:- The argument of Space() function is void type, so when this function is called
there are no argument can send to it. But ‘mCount’ argument is sending to Space()
function through return space(mCount); Statement.
Here return space (mCount); replaced by return space();
17. Create a class MAT which represents a matrix of size m x n. Define any two matrix operations for
MAT type objects.
Solution:-
18. Identify the error in the following program :-
i) #include<iostream.h>
Class Room
{
int width, height;
void setvalue(int w, int h)
{ width= w;
Height=h;
}
};

void main()
{ Room objRoom;
objRoom.width=12;
}
Solution:- void setvalue (in w, int l) function must be public.

ii) #include<iostream>
#define pi 3.14
int squareArea(int &);
int circleArea(int &);

void main()
{ int a=10;
cout<< squareArea(a)<<” “;
cout<< circleArea (a)<<” “;
cout<<a<<endl;
}

int squareArea(int & a)


{
return a*==a;
}

int circleArea(int & r)


{
return r=pi*r*r;
}

Solution:- This error can be resolved as follows:-

iii) #include<iostream>
int fun()
{
return 1;
}

float fun()
{
return 10.23;
}

void main()
{
cout<< (int) fun()<<’ ‘;
cout<<(float) fun()<<’ ‘ ;
}
Solution:-Here two functions are same except return type. Function overloading can be used using
different argument type but not return type.
This error can be resolved as follows:-

iv) #include<iostream.h>
int gValue=10;

void extra()
{
Cout<<gValue<<’ ‘;
}

void main()
{
extra();
{ int gValue=20;
cout<< gValue <<’ ‘;
cout<<: gValue<<’ ‘ ;
}
}
Solution:- Here cout<<: gValue<<’ ‘ ; is to be replaced with cout<<: :gValue<<’ ‘ ; (:: is scope resolution
operator)
This error can be resolved as follows:-
19. Write a class to represent a bank account which include the following members: (8mks)-3
Data members-
Name of the depositor , account number, type of account, balance amount in the account.
Member functions-
To assign initial value
To deposit an amount
To withdraw an amount after checking the balance
To display name and balance
Write a main program to test the program.
Solution:-
20. An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is
done by marking the candidate number on the ballot paper. Write a C++ program to read the ballots and
count the values for each candidate using a variable count. In case a number read is outside the range 1
to 5, the ballot should be considered as a spoilt vote and the program should count the number of spoilt
ballots (use classes and objects).
Solution:-
21. Create two classes DM and DB which stores the value of distance in meters and centimeters and
DB in feet and inches. Write a program that can read value for the class objects and add an object of
DM with another object of DB. Use a friend function to carry out the addition operation. Object that
store the result may be DM object or DB object depending on the units in which results are
required.
Solution:-
22. write a c++ program to create a class matrix and perform following operations on the matrix:
ii) Addition
iii) Multiplication
iv) Transpose
Solution:-
23. Write a C++ program to keep track of the number of objects of a class. Use the concept static data
members and static member functions.
Solution:-

24. What are characteristics of a friend function ? Demonstrate how a friend function can work as a
bridge between two classes.
Solution:- pg no:-125-126
Program 5.9

*****NOTE: ALL PAGE NUMBERS ARE FROM “OBJECT ORIENTED PROGRAMMING WITH C++ “
- E. BALAGURUSAMY (FOURTH EDITION)*****

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