ASSIGNMENT
OF : MCA 2030- OBJECT ORIENTED PROGRAMMING – C++
Question No 1. Write short notes on:
a) Inheritance
b) Polymorphism.
Inheritance:
Inheritance is one of the most powerful
feature of Object Oriented Programming languages that allows you to derive a
class from an existing class and inherit all the characteristics and behaviour
of the parent class. The feature allows easy modification of existing code and
also reuse code. The ability to reuse components of a program is import feature
for any programming language.
Inheritance feature has enabled to
distribute class libraries which allow the programmer to use the standard code
developed by some another company. Inheritance is the process or creating new
classes known as derived classes from the existing or base class. The feature
of the base class are said to be inherited by the derived class. The child
class has all the functionality of the parent class and has additional
functionalities of its own.
For example:
Consider
a base class Shape and its derived class Rectangle as
follows:
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
//
Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and
executed, it produces the following result:
Total area: 35
Polymorphism:
Operator overloading feature allows users
to define how basic operators work with objects. The operator + will be adding
two numbers when used with integer variables. However when used with user
defined string class + operator may concatenate two strings. Similarly same
functions with same function name can perform different actions depending upon.
Which object calls the function. This feature of C++ where same operators or
functions behave differently depending upon what they are operators overloading
is a kind of polymorphism OOP approach offers several advantages to the
programmers such as
v Code
can be reused in situations requiring customization.
v Program
modelling and development closer to real word situations and objects.
v Easy
to modify code.
v Only
required data binded to operations thus hiding data situations and functions.
For example:
Consider the following example where a
base class has been derived by other two classes:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for
the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle
tri(10,5);
//
store the address of Rectangle
shape = &rec;
//
call rectangle area.
shape->area();
//
store the address of Triangle
shape = &tri;
//
call triangle area.
shape->area();
return 0;
}
When the above code is compiled and executed,
it produces the following result:
Parent class area
Parent class area
Question No 2.Differentiate between
pass by value and pass by reference.
Call by Value
If data is passed by value, the data is copied from the variable
used in for example main() to a variable used by the function. So if the data
passed (that is stored in the function variable) is modified inside the
function, the value is only changed in the variable used inside the function.
All the operations in the function is then performed on the
function variable. The values in the variables declared in the main program
remains uncharged by the function operations. Let’s take a look at a call by value example:
passed-by-value:
template<class T>
bool find (stack<T> source, T value)
{
while (!source.isEmpty() &&
source.top() != value)
source.pop();
if (!source.isEmpty())
return true;
return false;
}
Passing by
Reference.
In passing
by reference, no copy of the variable is created. However, the variables in the
main program are referred to by different name is the function. Since no copy
is created, when the values in the function variables are modified, the values
in the variables an easy mechanism for modifying the variable by functions and
functions and also enables to return multiple variable
To pass
arguments by reference, all the variable names in the argument list should be
prefixed with and ampersand or address of operator during function declaration
and definition. The following example shows
the implementation of passing by reference. Let’s
take a look at a call by value example:
passed-by-reference :
template<class T>
bool find (const stack<T> &source, T value)
{
stack<T> temp = source;
while (!temp.isEmpty() && temp.top()
!= value)
temp.pop();
if (!temp.isEmpty())
return true;
return false;
}
Question No 3. Differentiate between Constructors
and Destructors.
Constructors:
Constructors are member functions of a
class which have same names as a class name. Constructors are called
automatically whenever an object of the class is created. This feature makes it
very useful to initialize the class data members whenever a new object is
created. It also can perform any other function that needs to be performed for
all the objects of the class without explicitly specifying it.
For example:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
Destructors:
A destructor is
a special member function of a class that is executed whenever an object of
it's class goes out of scope or whenever the delete expression is applied to a
pointer to the object of that class.
A destructor will have exact same name
as the class prefixed with a tilde (~) and it can neither return a value nor
can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing
memories etc.
Following example explains the concept
of destructor:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line();
// This is the destructor:
declaration
private:
double length;
};
// Member functions
definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for
the program
int main( )
{
Line line;
//
set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted
Question No 4.What are the advantages of
Polymorphism? How it can be
implemented?
Polymorphism:
Operator overloading feature allows users
to define how basic operators work with objects. The operator + will be adding
two numbers when used with integer variables. However when used with user
defined string class + operator may concatenate two strings. Similarly same
functions with same function name can perform different actions depending upon.
Which object calls the function. This feature of C++ where same operators or
functions behave differently depending upon what they are operators overloading
is a kind of polymorphism OOP approach offers several advantages to the
programmers
Advantage of Polymorphism
v Code
can be reused in situations requiring customization.
v Program
modelling and development closer to real word situations and objects.
v Easy
to modify code.
v Only
required data binded to operations thus hiding data situations and functions.
v It helps the programmers to reuse the
code and classes once written, tested and implemented. They can be reused in
many cases.
v Single variable can be used to store multiple
data types.
v It reduces coupling.
The
word polymorphism means having many forms. Typically,
polymorphism occurs when there is a hierarchy of classes and they are related
by inheritance.
C++ polymorphism means that a call to a member function will cause
a different function to be executed depending on the type of object that
invokes the function.
Consider the following example where a base class has been derived
by other two classes:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Parent class area
Parent class area
Question No 5. Differentiate between
Containers and Iterators.
Containers:
A container is a way stored data is organized in memory, for example an array of elements.Container classes are building blocks used to create objectoriented programs, and they make the internals of a program much easier to construct.
A container class describes an object that holds other objects.Container classes are so important that they were considered fundamental to early objectoriented languages.The C++ approach to containers is based on templates.
1.
The containers in the Standard C++ library represent a broad range of data structures designed to work well with the standard algorithms and to meet common software development needs.
2.
Sequential containers: vector, list and deque; They store elements in client
visible order
Associative containers: map, multimap, set and multiset.Containers Adapters: queue, priorityqueue and stack
3.
An associative container is nonsequential but uses a key to access elements. The keys, typically a number or a string, are used by the container to arrange the stored objects in a specific order, for example in a dictionary the entries are ordered alphabetically.
For example:
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main(void)
{
set<int> intset;
for(int i = 0; i < 250; i++)
for(int j = 0; j < 24; j++)
intset.insert(j);
cout <<"Set Size "<<intset.size()<<endl;
cout <<"Contents"<<endl;
copy(intset.begin(),intset.end(),
ostream_iterator<int>(cout, ", "));
cout<<"\n";
}
Iterators:
Iterators are a generalization of the concept of pointers, they point to elements in a container, for example you can increment an iterator to point to the next element in an array.An iterator is an abstraction for genericity.It works with different types of containers without knowing the underlying structure of those containers.
1.
Most containers support iterators, so you can say
Iterators
2.
Iterator is a generation of pointer
3.
It is an object belonging to a class with the prefix * defined on it
4.
So that, if p in an iterator over a container, *p is an object in the container.
5.
You can think of iterator as pointing to a current object at any time
The use of containers.
6.
They give us control over collections of objects, especially dynamic objects.
7.
Gives a simple mechanism for creating, accessing and destroying without explicitly programming algorithms to do these operation add object
find object remove object is
8.
Empty Container
“Iterator” methods allow us to iterate throw the container.
For example:
using namespace std;
void CountUniqueWords(const char* fileName)
{
ifstream source(fileName);
if(!source)
{ cerr<<"error opening file\n";
exit(EXIT_FAILURE);
}
string word;
set<string> words;
while(source >> word)
words.insert(word);
cout << "Number of unique words:"<< words.size() << endl;
copy(words.begin(), words.end(),ostream_iterator<string>(cout, "\n"));
}
int main(int argc, char* argv[])
{
if(argc > 1) CountUniqueWords(argv[1]);
else
cerr<<"Usage "<<argv[0]<<" file name"<<endl;
}
Question No 6. Describe the two basic
exception handling models.
Exception handling:
An exception is a problem that arises during the execution of a
program. A C++ exception is a response to an exceptional circumstance that
arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to
transfer control from one part of a program to another. C++ exception handling
is built upon three keywords: try,
catch, and throw.
·
throw: A program throws an exception when
a problem shows up. This is done using a throwkeyword.
·
catch: A program catches an exception with
an exception handler at the place in a program where you want to handle the
problem. The catch keyword indicates the catching of an
exception.
·
try: A try block identifies a block of code for
which particular exceptions will be activated. It's followed by one or more
catch blocks.
Assuming a block will raise an
exception, a method catches an exception using a combination of the tryand catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like
the following:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception
in different situations.
Throwing Exceptions:
Exceptions can be thrown anywhere
within a code block using throw statements. The operand of the throw
statements determines a type for the exception and can be any expression and
the type of the result of the expression determines the type of exception
thrown.
Following is an example of throwing an exception when dividing by
zero condition occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions:
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception
of ExceptionName type. If you want to specify that a
catch block should handle any type of exception that is thrown in a try block, you
must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows:
try
{
// protected code
}catch(...)
{
// code to handle any exception
}
The following is an example, which throws a division by zero
exception and we catch it in catch block.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception
of type const char*, so
while catching this exception, we have to use const char* in catch block. If we
compile and run above code, this would produce the following result:
Division by zero condition!
…………………………………………………………………………
No comments:
Post a Comment