You are on page 1of 15

Affiliated to, Tribhuvan University

Nayabazar, Khusibun Development Area


Tel: 4360180, 360182
E - Add: - pcmit@wlink.com.np
URL: - www.prime.edu.np

Object Oriented Programming,


Paper on Prominence of OOP, C++

Submitted By: - Submitted To: -


Geshan Manandhar Mr. Arun Joshi
“03 - 00097 - 2” Lecturer, OOP
BIM 3rd Semester Prime College
Prime College

Date OF Submission: -
Paper on Prominence of OOP

21st Dec 2004


What is OOP (Object Oriented Programming)?

Previously in structured programming or procedure oriented programming we


used to emphasize on doing things, large problems were broken into smaller
segments (functions). The data was open to all especially global variables could be
altered with no restrictions. So there was a sense of unrestricted access. It was no
where near to the real world. But then appeared OOP (Object Oriented
Programming), it was much like the real world with actual objects. The real world
was complex with objects having not only attributes but also behavior. This concept
is priorized in OOP. The OBJECT was born. An object is a software bundle of related
variables and methods abstracted as per need from any real life object be it
physically present (ex: car) or a logical entity (ex: bank account). Software objects
are often used to models real-world objects you find in everyday life as exemplified
above. So the basic idea that lies in OOP is that it combines (encapsulates) data and
functions in a single unit known as object. Objects are based on class and a class is a
blueprint or prototype that defines the variables and the methods common to all
objects of a certain kind.
Now, let’s analyze what OOP focuses on,
1> Emphasis on data rather than procedures and functions.
2> Use of Objects for cleared and better programs.
3> Functions can operate as per it is defined for a class.
4> Easy addition of functions as per need.
5> Capability of data hiding1, inheritance2, overloading3 etc.

Features of OOP (C++)


The main features of OOP or Object Orientation are as follows:
1: Abstraction
2: Encapsulation
3: Inheritance
4: Polymorphism (Overloading)
5: Dynamic Binding & Message Passing

1: Abstraction= literally means “a general concept formed by extracting


common features from specific examples”. So in OOP also we form an abstract
of the real life objects by abstracting only the attributes we need and leaving all
the other unnecessary details and explanation. It’s simply keeping what we
need (from program’s point of view) and leaving all the unwanted information.
Bookwise”Abstraction is the process of highlighting the essential, inherent
aspects of an entity while ignoring irrelevant details”.
It is done to shape up a real life object to be fit as our program object.
It selects only the prominent qualities of the object that will represent the
object in our program as per need. Classes use the concept of abstraction and
are defined as a list of abstract(ed) attributes. In other aspect it equates what
to operate with than how to operate with as in procedural language. It can be
plainly explained by an example analyzing a real object as Man. A man has may
many qualities/ attributes and many things he can do. For ex: he has his
height, weight, age many other measurements, his IQ, EQ etc etc. He could
1
Data Hiding: A property where the internal data structure is hidden form the rest of the program.
2
Inheritance: A relationship between classes where the derived class inherits attributes of base class.
3
Overloading: A language feature that allows a function or operator to be given more than one definition.

Accomplished by © Geshan Manandhar ® ™ 2


Paper on Prominence of OOP

perform many tasks like talk, walk, pay, eat, run sleep etc etc, but as per the
need of the program we abstract a class called man. We only include the
attributes that have some relation with our program. The chosen attributes and
behavior (tasks) must have connection with about what we are making the
program. Like in of salary of an employee man we may call behavior/method
like give salary etc or in case of student man we may call method like admit,
promote etc. So with proper abstraction we can get the class and object we
want, resulting the desired result we want.

2: Encapsulation= is the coupling of data and function/method together


into a single component. Data cannot be accessible to the outside class and
only those functions which are stored in/for the class can access it. Data
encapsulation, sometimes referred to as data hiding, is the mechanism whereby
the implementation details of a class are kept hidden from the user. The user
can only perform a restricted set of operations on the hidden members of the
class by executing special functions commonly called methods. The actions
performed by the methods are determined by the designer of the class, who
must be careful not to make the methods either overly flexible or too
restrictive. This idea of hiding the details away from the user and providing a
restricted, clearly defined interface is the underlying theme behind the concept
of an abstract data type. It is also preventing unauthorized access to some
piece of information or functionality as per need. In other words, the ability to
package data with functions allows you to create a new data type is often called
encapsulation. An existing data type may have several pieces of data packaged
together. For example a float has an exponent, a mantissa, and a sign bit. You
can tell it to do things: add to another float or to an int, and so on. It has
characteristics and behavior as mentioned above. It is well explained in the
figure in the cover page. The inner o of the OOP indicates the covering of the
private attributes and the contents of the outer (bigger) o is the methods to
access the attributes.

3: Inheritance= Inheritance is the mechanism by which specific classes


are made from more general ones. The child or derived class inherits all the
features of its parent or base class, and is free to add features of its own. In
addition, this derived class may be used as the base class of an even more
specialized class. Inheritance, or derivation, provides a clean mechanism
whereby common classes can share their common features, rather than having
to rewrite them. For example, consider a student class which is represented by
roll no and name its derived class may have new variable like background for
science or commerce. Let’s visualise another example of vehicle.

Accomplished by © Geshan Manandhar ® ™ 3


Paper on Prominence of OOP

Fig 1.1
Moreover, each subclass inherits state (in the form of variable declarations)
from the superclass. You are not limited to just one layer of inheritance. The
inheritance tree, or class hierarchy, can be as deep as needed. Methods and
variables are inherited down through the levels. In general, the farther down in
the hierarchy a class appears, the more specialized its behavior. A think I would
like to add here is “One of the most compelling features about C++ is
codereuse. But to be revolutionary, you need to be able to do a lot more than
copy code and change it”.

Inheritance offers the following benefits:


Ω Subclasses provide specialized behaviors from the basis of common
elements provided by the superclass. Through the use of inheritance,
programmers can reuse the code in the superclass many times.
Ω Programmers can implement superclasses called abstract classes that
define "generic" behaviors. The abstract superclass defines and may
partially implement the behavior, but much of the class is undefined and
unimplemented. Other programmers fill in the details with specialized
subclasses.

4: Polymorphism (Overloading) = Polymorphism means the ability to


take more than one form with the same name. An operation may exhibit
different behaviors in different instances. The behavior depends on the data
types used in the operation with relation to return type also. Polymorphism is
extensively used in implementing Inheritance. The simplest explanation is one
name many forms. It is utilized using overloaded functions and operators. Let’s
see a draw function being overloaded for polymorphism.

Accomplished by © Geshan Manandhar ® ™ 4


Paper on Prominence of OOP

Fig :1.2
Here the draw function has the same name but will perform different
operations per the object it is called for. Like for circle it will draw a circle for
square a square and for triangle a triangle, likewise for erase. The funda behind
this is the variation in message (argument) passed to that method and its
return type difference. So this proves that, polymorphism is difficult to explain,
but easy to demonstrate. Polymorphism allows improved code organization and
readability as well as the creation of extensible programs that can be “grown”
not only during the original creation of the project, but also when new features
are desired. (PS: Overloading is dealt in detail on the topic Function
Overloading and Inline Functions Pg # 5.)

5: Dynamic Binding and Message Passing= The linking of a


procedure call to the code it is to be executed with relation to the call is termed
binding. Reverse of static binding, dynamic binding (aka late binding) is the
code associated with the given method call is unknown until the time of the call
at run-time itself. The function call is related with polymorphism and
inheritence. Clearly, if the type T of a variable with name N is implicitly
associated by its content, we say, that N is dynamically bound to T. The
association process is called dynamic binding.
Consider the draw function in fig 1.2, by the use of inhertence all the objects
can call use this function but it’s definition will be unique to the natue of the
object or the arguments passed.
Object Oriented Programming comprises of objects and there communication.
So messages are passed for communication which previously was termed as
argument passing in procedural language like C. Object as an abstract of real
object the communication also takes palce as in the real world as people pass
messages to one another. In fig 1.2 the circle object is passed draw message to
do the action.

Accomplished by © Geshan Manandhar ® ™ 5


Paper on Prominence of OOP

C++ & its Features in relation with OOP!


C ++ is an object oriented programming language developed by Bjarne Stroustrup of
Bell Labs in New Jersey in early 1980’s. It is considered as the super set of ‘C’
because C++ (CPP) compiler compiles C code as well. Some of the features their
whys, pros and cons will be discussed in this paper. The featues to be analyzed are
as follows:
1. Inline Function & Function Overloading
2. Classes and Objects
3. Constructor & Destructors

1. Inline Function & Function Overloading= Inline literally means


“Being next in a line of succession” in OOP it can be transformed as when we
call a normal function it jumps to the place where the function is defined this
interrupts the sequential flow. If we could rewrite the code of function definition
at the place of functin call it would not break the sequential flow of the
program. Functions are used to make programms small and clear but due to
internal complexites it takes more time to execute. So inline functions can be a
solution that will keep up the size and clarity aspect as well be executed fast. A
thing to notice is that, we should make the definition of the function small so as
the achieve the above mentined objective. There is use of keyword inline to
indicate that the functionis inline.

The "inline" keyword is merely a hint to the compiler or development


environment. Not every function can be inlined. Some typical reasons why
inlining is sometimes not done include:

- The function calls itself, that is, is recursive

- The function contains loops such as for(;;) or while()

- The function size is too large

a. Why?
It is used to keep up the size and clarity aspect of the normal function
as well as not break the flow of the program and not cost much time.
On in explaind version: It's definitely fewer keystrokes to inline a
function. However, another good reason to inline is that you can
sometimes speed up your program by inlining the right function.
Instead of calling the function every time it is invoked, the compiler
will replace the function call with a copy of the function body. If it's a
small function which gets called a lot, this can sometimes speed things
up.

Depending on the function, it can also be easier to read inline. If it's a


function like the following:

class Math { // class declaration


public:
int addTwoIntegers(int a, int b); // function declaration
};

int Math::addTwoIntegers(int a, int b) { // function definition

Accomplished by © Geshan Manandhar ® ™ 6


Paper on Prominence of OOP

return a + b;
}

it's probably easier to read if it's inlined:


class Math { // class declaration
public:
int addTwoIntegers(int a, int b) {return a + b; } // inlined function
}; // (combined declaration and definition)

b. Pros & Cons:


Faster program execution due to use of small functions.
But may take longer time to execute if function are big.
(PS underline = pro , Italic = Con)

Ex2:
inline add (int x, int y) {return(x+y);}
The above function where called will be replaced by the body of the
function.

Overloading Functions: is a concept used in OOP to use the same function for
may objectives/job. Plainly, it is method with the same name has two or more
definitions as per the arguments passed and data type returned. Even
operators like +,-,++ etc can be overloaded to do desired operation on self
created objects(data types).
A problem arises when mapping the concept of nuance in human language
onto a programming language. Often, the same word expresses a number of
different meanings, depending on context. That is, a single word has multiple
meanings – it’s overloaded. This is very useful, especially when it comes to
trivial differences. You say “wash the shirt, wash the car.” It would be silly to
be forced to say, “shirt_wash the shirt, car wash the car” just so the hearer
doesn’t have to make any distinction about the action performed. Most human
languages are redundant, so even if you miss a few words, you can still
determine the meaning. We don’t need unique identifiers – we can deduce
meaning from context. Most programming languages, however, require that
you have a unique identifier for each function. If you have three different types
of data that you want to print: int, char, and float, you generally have to create
three different function names, for example, print_int( ), print_char( ), and
print_float( ). This loads extra work on you as you write the program, and on
readers as they try to understand it. In C++, another factor forces the
overloading of function names: the constructor. Because the constructor’s
name is predetermined by the name of the class, it would seem that there can
be only one constructor. But what if you want to create an object in more than
one way? For example, suppose you build a class that can initialize itself in a
standard way and also by reading information from a file. You need two
constructors, one that takes no arguments (the default constructor) and one
that takes a string as an argument, which is the name of the file to initialize the
object. Both are constructors, so they must have the same name: the name of
the class. Thus function overloading is essential to allow the same function
name – the constructor in this case – to be used with different argument types.
Although function overloading is a must for constructors, it’s a general
convenience and can be used with any function, not just class member
functions. In addition, function overloading means that if you have two libraries

Accomplished by © Geshan Manandhar ® ™ 7


Paper on Prominence of OOP

that contain functions of the same name, they won’t conflict as long as the
argument lists are different.

More clearly, Function overloading is the practice of declaring the same


function with different signatures. The same function name will be used with
different number of parameters and parameters of different type. But
overloading of functions with different return types are not allowed.

For example in this C++ Tutorial let us assume an AddAndDisplay function


with different types of parameters.

//C++ Tutorial - Sample code for function overloading


void AddAndDisplay(int x, int y)
{
cout<<" C++ - Integer result: "<<(x+y);
}

void AddAndDisplay(double x, double y)


{
cout<< " C++ - Double result: "<<(x+y);
}

void AddAndDisplay(float x, float y)


{
cout<< " C++ - float result: "<<(x+y);

Some times when these overloaded functions are called, they might cause
ambiguity errors. This is because the compiler may not be able to decide what
signature function should be called.

If the data is type cast properly, then these errors will be resolved easily.
Typically, function overloading is used wherever a different type of data is to be
dealt with. For example this can be used for a function which converts farenheit
to celsius and vice versa. One of the functions can deal with the integer data,
other can deal float for precision etc.,

2. Class and Objects= Typically, A class is a blueprint, or prototype,


that defines the variables and the methods common to all objects of a certain
kind. OOP sees everything as objects, in the real world; you often have many
objects of the same kind. For example, your bicycle is just one of many bicycles
in the world. Using object-oriented terminology, we say that your bicycle object
is an instance of the class of objects known as bicycles. Bicycles have some
state (current gear, current cadence, two wheels) and behavior (change gears,
brake) in common. However, each bicycle's state is independent of and can be
different from that of other bicycles.

When building bicycles, manufacturers take advantage of the fact that bicycles
share characteristics, building many bicycles from the same blueprint. It would
be very inefficient to produce a new blueprint for every individual bicycle
manufactured.

Accomplished by © Geshan Manandhar ® ™ 8


Paper on Prominence of OOP

In object-oriented software, it's also possible to have many objects of the same
kind that share characteristics: rectangles, employee records, video clips, and
so on. Like the bicycle manufacturers, you can take advantage of the fact that
objects of the same kind are similar and you can create a blueprint for those
objects. A software blueprint for objects is called a class.

The class for our bicycle example


would declare the instance
variables necessary to contain the
current gear, the current cadence,
and so on, for each bicycle object.
The class would also declare and
provide implementations for the
instance methods that allow the
rider to change gears, brake, and
change the pedaling cadence, as
shown in the next figure 1.4.
Fig 1.3

After you've created the bicycle


class, you can create any number
of bicycle objects from the class.
When you create an instance of a
class, the system allocates
enough memory for the object
and all its instance variables. Each
instance gets its own copy of all
the instance variables defined in
the class.
Fig 1.4

Objects= the instance of class. In other words, an object is a software bundle


of related variables and methods. Software objects are often used to model
real-world objects you find in everyday life.

1. Everything is an object. Think of an object as a fancy variable; it


stores data, but you can “make requests” to that object, asking it to perform
operations on itself. In theory you can take any conceptual component in the
problem you’re trying to solve (dogs, buildings, services, etc.) and represent
it as an object in your program.

2. A program is a bunch of objects telling each other what to do by


sending messages. To make a request of an object, you “send a message”
to that object. More concretely, you can think of a message as a request to
call a function that belongs to a particular object.

3. Each object has its own memory made up of other objects. Put
another way, you create a new kind of object by making a package
containing existing objects. Thus, you can build complexity in a program while
hiding it behind the simplicity of objects.

Accomplished by © Geshan Manandhar ® ™ 9


Paper on Prominence of OOP

4. Every object has a type. Using the parlance, each object is an instance
of a class, where “class” is synonymous with “type.” The most important
distinguishing characteristic of a class is “what messages can you send to it?”

5. All objects of a particular type can receive the same messages. This is
actually a very loaded statement, as you will see later. Because an object of
type “circle” is also an object of type “shape,” a circle is guaranteed to receive
shape messages. This means you can write code that talks to shapes and
automatically handle anything that fits the description of a shape. This
substitutability is one of the most powerful concepts in OOP.

Objects provide a logical grouping of data and associated operations. Objects


do a great job of encapsulating the data items within, because the only access
to them is through the methods, or associated procedures.

Classes VS Objects=

Many people get confused by the difference between class and object. The
difference is simple and conceptual. A class is a template for objects. A class
defines object properties including a valid range of values, and a default value.
A class also describes object behavior. An object is a member or an "instance"
of a class. An object has a state in which all of its properties have values that
you either explicitly defines or that are defined by default settings.

This subtle conceptual difference between classes and objects shows why there
is a tendency to want to use them interchangeably.

3. Constructors and Destructors= Constructor is a function which has


the same name as the class used for special function of costructing an
instance/object of the class to which it belongs to. It allocates the enough
memory space required for data in the object. Constructors can be overloaded
and can also be used as initializers. It is always defined in the public section of
the class and doesn’t even return void but may take arguments as per need.
When the class is created, the constructor is called to initialize the object. The
constructor may be overloaded, in which case the most appropriate constructor
is selected when the object is initialized.
Constructor Types:-
a. The Default Constructor
b. User defined Constructor (Parameterized and Non-
Parameterized)
c. Copy Constructor

a. The Default Constructor: is a constructor which is automatically


created by the compiler to reserver required memory address for an
object of any class. It is also called implicit class constructor. It is
hidded and takes no arguments. It is automatically called.

b. User Defined Constructor: is a kind of constructor defined by the


user, it is mainly used to initalize the state value of an object on
creation. It is defined and called explicitly. Inverse of default
constructor it doesn’t reserve memory for the object but it’s code is

Accomplished by © Geshan Manandhar ® ™ 10


Paper on Prominence of OOP

mainly used for data initiallization. We are able to define more than
one constructor in a class as per the need. The user defined
constructor with no arguments, blank body and no return type can be
compared with the default one.

The user defined constructors can be classified into two parts, they
are:

1: Parameterized: The user defined constructor that


takes arguments. It provied scope to initialize the state value of
the objects. It depends on the programmer to pass what and
get results.
2: Non Parameterized: The type of user defined
constructor that takes no arguments/message. It provied no
chance of initilization of state values but may ask user to input
the initial’s as desired.

c. Copy Constructor: is a type of construcor that copies the state values


of an already created object to a newly instantiated one. It uses
reference to do so. Copy constructors are also sub divided into two
categories:
1: Default Copy Constructor
2: User Defined Copy Constructor

(PS: The example of constructor is given after destructor with needed


comments)

Destructors: is also a special kind of function that as the name implies is used
to destroy the object created by its counter part the constructor. Destructors
also have the same name as the constructors but it is preceded with a tilde ~.
For ex if a destructor is to be defined of class man then it should have name
~man.

Destruction of objects takes place when the object leaves its scope of definition
or is explicitly destroyed. The latter happens, when we dynamically allocate an
object and release it when it is no longer needed.

The destructor as the constructor never takes any agruments of retuns


anything(not even void). Destructor removes the object from the memory of
the computer. Like the contructor destructors are also of two varieties, they are
a. Default Destructor
b. User Defined Destructor

a. Default Destructor: is a destructor implicitly created by the


compiler. Its body is always hidden and it is called implicitly to
destroy the object when it’s live is over i.e, out of the scope. It is
used to free up the memory space taken by that particular object in
the time of creation by the constructor and while it was being used
for manipulation. It is very useful in applications like database

Accomplished by © Geshan Manandhar ® ™ 11


Paper on Prominence of OOP

management system where the database is to be freed up for other


operations.
b. User Defined Destructor: is a destructor that frees up the
memory space occupied by the object destroyed. But it doesn’t take
any argument or returns any thing. It can be defined to confirm the
death of the object only. No operations can be carried out by this
function.

Example of constructor and destrucor with in a program.

/* Program Coded to see function of Lion Class with use of construcor its types and
destructor
Coded by GESHAN MANANDHAR,03-00097-2, BIM 3rd Sem, Prime College
as at 12/12/04 for OOP(C++) */

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

/*start of class definition*/


class lion
{
private: //private attributes
int ln;
float wt;
float h;

public: //public methods

void sleeping()
{
cout<<"\nThe lion No "<<ln<<" is Sleeping."<<endl; }

void hunting()
{
cout<<"\nThe lion No "<<ln<<" is hunting. "<<endl; }

void running()
{
cout<<"\nThe lion No "<<ln<<" is running. "<<endl; }

lion() //A non parameterized constructor thar works like default one
{ cout<<"Calling Default constructor.Lion Created.\n";
cout<<"Give no to lion: ";
cin>>ln;
cout<<"Give weight of Lion: ";
cin>>wt;
cout<<"Give lion's Height: ";
cin>>h;

Accomplished by © Geshan Manandhar ® ™ 12


Paper on Prominence of OOP

} //but this also initializes the state values.

lion(lion &lioned) //a copy constructor.


{
ln=lioned.ln;
wt=lioned.wt;
h=lioned.h;

cout<<"Values inputted using copy constructor.\n";

lion(int no,float w,float ht)// a parameterized constructor.


{
ln=no;
wt=w;
h=ht;

cout<<"\n The use of parameterized constructor.\n"<<endl;


}

void disp()
{
cout<<"\nLion NO: "<<ln<<endl;
cout<<"Lion Weight: "<<wt<<endl;
cout<<"Lion Height: "<<h<<endl;
cout<<endl;

}
~lion() //a user defined destructor to see the effects.
{
cout<<"Lion No "<<ln<<" destroyed by destructor."<<endl;
}

};

void main()
{
clrscr();

lion l1,l2,l3;
lion l6(7,25.52,35.25);

{/*scope defined to see the work of destructor*/

l1.running();

l2.hunting();

Accomplished by © Geshan Manandhar ® ™ 13


Paper on Prominence of OOP

l3.sleeping();

lion l5=l3;

cout<<"Info of lion3"<<endl;
l3.disp();

cout<<" Info of Lion5"<<endl;


l5.disp();

cout<<"Notice, the info of L3 & L5 are same using copy constructor.\n"<<endl;

l6.disp();
}
getch();

}//main ends.

Accomplished by © Geshan Manandhar ® ™ 14


Paper on Prominence of OOP

4. References, Bibliography:

I. Object Oriented Programming in C++, 3rd Edn: Robert Lafore.


II. Object Oriented Programming with C++, 2nd Edn: E Balagurusamy
III. Notes provided by our Lecturer, Mr. Arun Joshi
IV. Encyclopedia 2003
V. A PDF file called thinking in C++.

Websites:

I~ http://www.cs.mun.ca/~donald/bsc/node14.html – A C++ tutorial.


II ~ http://java.sun.com/docs/books/tutorial/java/concepts/ - Concepts of OOP as per
JAVA.
III ~ http://gee.cs.oswego.edu/dl/oosdw3/index.html - page on OOP.
IV ~ http://www.icce.rug.nl/docs/cplusplus/ - a C++ tutorial
V~ http://www.cplusplus.com – A C++ Tutor Site.
VI ~ http://www.codersource.net – A website giving C++ Source codes and tutorials
VII ~ http://www.cplus.about.com – C ++ described in about.com

Accomplished by © Geshan Manandhar ® ™ 15

You might also like