Oop Mod1@Azdocuments - in
Oop Mod1@Azdocuments - in
Simple, non-OOP programs may be one "long" list of statements (or commands). More complex
programs will often group smaller sections of these statements into functions or subroutines each of
which might perform a particular task. With designs of this sort, it is common for some of the
program's data to be 'global', i.e. accessible from any part of the program. As programs grow in size,
allowing any function to modify any piece of data means that bugs can have wide-reaching effects.
In contrast, the object-oriented approach encourages the programmer to place data where it is not
directly accessible by the rest of the program. Instead, the data is accessed by calling specially
written functions, commonly called methods, which are either bundled in with the data or inherited
from "class objects." These act as the intermediaries for retrieving or modifying the data they control.
The programming construct that combines data with a set of methods for accessing and managing
those data is called an object. The practice of using subroutines to examine or modify certain kinds of
data was also used in non-OOP modular programming, well before the widespread use of object-
oriented programming.
An object-oriented program will usually contain different types of objects, each type corresponding
to a particular kind of complex data to be managed or perhaps to a real-world object or concept such
as a bank account, a hockey player, or a bulldozer. A program might well contain multiple copies of
each type of object, one for each of the real-world objects the program is dealing with. For instance,
there could be one bank account object for each real-world account at a particular bank. Each copy of
the bank account object would be alike in the methods it offers for manipulating or reading its data.,
but the data inside each object would differ reflecting the different history of each account.
Objects can be thought of as wrapping their data within a set of functions designed to ensure that the
data are used appropriately, and to assist in that use. The object's methods will typically include
checks and safeguards that are specific to the types of data the object contains. An object can also
offer simple-to-use, standardized methods for performing particular operations on its data, while
concealing the specifics of how those tasks are accomplished. In this way alterations can be made to
the internal structure or methods of an object without requiring that the rest of the program be
modified. This approach can also be used to offer standardized methods across different types of
objects. As an example, several different types of objects might offer print methods. Each type of
object might implement that print method in a different way, reflecting the different kinds of data
each contains, but all the different print methods might be called in the same standardized manner
from elsewhere in the program. These features become especially useful when more than one
programmer is contributing code to a project or when the goal is to reuse code between projects.
Object-oriented programming has roots that can be traced to the 1960s. As hardware and software
became increasingly complex, manageability often became a concern. Researchers studied ways to
maintain software quality and developed object-oriented programming in part to address common
problems by strongly emphasizing discrete, reusable units of programming logic. The technology
focuses on data rather than processes, with programs composed of self-sufficient modules ("classes"),
each instance of which ("objects") contains all the information needed to manipulate its own data
structure ("members"). This is in contrast to the existing modular programming that had been
dominant for many years that focused on the function of a module, rather than specifically the data,
but equally provided for code reuse, and self-sufficient reusable units of programming logic,
enabling collaboration through the use of linked modules (subroutines).
Not all of these concepts are to be found in all object-oriented programming languages. For example,
object-oriented programming that uses classes is sometimes called class-based programming,
while prototype-based programming does not typically use classes. As a result, a significantly
different yet analogous terminology is used to define the concepts of object andinstance.
Benjamin C. Pierce and some other researchers view as futile any attempt to distill OOP to a minimal
set of features. He nonetheless identifies fundamental features that support the OOP programming
style in most object-oriented languages:[16]
Dynamic dispatch when a method is invoked on an object, the object itself determines what
code gets executed by looking up the method at run time in a table associated with the object.
This feature distinguishes an object from an abstract data type (or module), which has a fixed
(static) implementation of the operations for all instances. It is a programming methodology that
gives modular component development while at the same time being very efficient.
Encapsulation (or multi-methods, in which case the state is kept separate)
Subtype polymorphism
Object inheritance (or delegation)
Open recursion a special variable (syntactically it may be a keyword), usually
called this or self, that allows a method body to invoke another method body of the same object.
This variable is late-bound; it allows a method defined in one class to invoke another method that
is defined later, in some subclass thereof.
Similarly, in his 2003 book, Concepts in programming languages, John C. Mitchell identifies four
main features: dynamic dispatch, abstraction, subtype polymorphism, and inheritance. Michael Lee
Scott in Programming Language Pragmatics considers only encapsulation, inheritance and dynamic
dispatch.
Classes of objects
Instances of classes
Methods which act on the attached objects.
Message passing
Abstraction
A Look at Procedure Oriented Programming.
Conventional programming, using high level languages such as COBOL,FORTRAN and C,is
commonly known as procedure oriented programming (POP). In the POP approach, the problem is
viewed as a sequence of things to be done such as reading,calculating and printing. A number of
functions are written to accomplish these tasks. The primary focus is on functions. A typical structure
for procedural programming is shown in the fig 1.1. The technique of hierarchical decomposition has
been used to specify the tasks to be completed for solving a problem.
Procedure Oriented programming basically consists of writing a list of instructions (or actions) for
the computer to follow, and organizing these instructions into groups known as functions. While
concentrating on the development of functions, very little attention is given to the data that are being
used by various functions. What happens to the data? How are they affected by the functions that
work on them?
DRAWBACKS:
In a multi-function program, many important data items are placed asglobal so that they may be
accessed by all the functions. Each function may have its own local data. Global data are more
vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify
what data is to be used by which function. In case we need to revise an external data structure, we
also need to revise all functions that access the data. This provides an opportunity for bugs to creep
in.
Another serious drawback is that it does not model real world problems very well. This is because
functions are action oriented and do not really correspond to elements of the problem.
Thus an object is considered to be a partitioned area of computer memory that stores data and set of
operations that can access that data. Since memory partitions are independent, the objects can be used
in a variety of different programs without modifications.
Objects
Objects are the basic run time entities in an object oriented system. They may represent a person, a
place , a bank account, a table of data or any item that the program has to handle. They may also
represent user defined data such as vectors, time and lists. Programming problem is analyzed in
terms of objects and the nature of communication between them. Program objects should be chosen
such that they match closely with the real world objects. Objects take up space in the memory and
have an associated address like a record in Pascal or a structure in C.
When a program is executed, the objects interact by sending messages to each other. For example, If
tomer object may send a
message to account object requesting for the bank balance. Each object contains data and code to
manipulate the data. Objects can interact without having to know each others data or code. It is
sufficient to know the type of messages accepted, and the type of response returned by the objects.
Classes
We just mentioned that objects can contain data, and code to manipulate that data. The entire set of
data and code of an object can be made a user defined data type with the help of a class. Infact
objects are variables of the type class. Once a class has been defined, we can create any number of
objects belonging to that class. Each object is associated with the data of type class with which they
are created. A class is thus a collection of objects similar type. For example mango,apple, and orange
are members of the class fruit. Classes are user defined data types and behave like the built in types
of a programming language. The syntax used is no different than the syntax used to create an integer
object in C. If fruit has been defined as a class, then the statement
fruit mango;
will create an object mango belonging to the class fruit.
division is that each derived class shares common characteristics with the class from which it is
derived as illustrated in fig 1.4.
In OOP, the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new class
from the existing one. The new class will have the combined features of both the classes. The real
appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that
is almost, but not exactly, what he wants, and to tailor the class in such a way that it does not
introduce any undesirable side-effects into the rest of the classes.
Note that each sub-class defines only those features that are unique to it. Without the use of
classification, each class would explicitly include all its features.
Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a greek term means ability to take
more than one form. An operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. For example, consider the operation of
addition. For two numbers the operation will generate a sum. If the operands are strings,then the
operation would produce a third string by concatenation. The process of making an operator to
exhibit different behaviors in different instances is known a operator overloading.
Fig 1.5 illustrates that a single function name can be used to handle different number and different
types of arguments. This is something similar to a particular word having several different meanings
depending on the context. Using a single function name to perform different types of tasks is known
as function overloading.
Polymorphism plays an important role in allowing objects having different internal structures to share
the same external interface. This means that a general class of operations may be accessed in the
same manner even though specific actions associated with each operation may differ. Polymorphism
is extensively used in implementing inheritance.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure
call is not known until the time of the call at rub-time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the dynamic type of
that reference.
fig 1.5. By inheritance, every object will have this procedure. Its
algorithm is, however, unique to each object and so the draw procedure will be redefined in each
class that defines the object. At run-time, the code matching the object under current reference will
be called.
Message passing
An object- oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language,therefore involves the following basic steps:
1. Creating classes that define objects and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people pass messages to one another. The concept of message passing makes it easier to talk about
building systems that directly model or simulate their real-world counterparts.
A message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired result. Message passing
involves specifying the name of the function (message) and the information to be sent.
Example:
Benefits of OOPs
Through inheritance, we can eliminate redundant code and extend the use of exiting classes.
We can build programs from the standard working modules that communicate with one
another,rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
It is possible to have multiple instances of an object to co-exist without any interference.
It is possible to map objects in the problem domain to those in the program.
It is easy to partition the work in a project based on objects.
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to capture more details of a model on
implementable form.
Object oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface descriptions
with external systems much simpler.
Software complexity can be easily managed.
In other words:
x = x+1; is the same as ++x; and x = x-1; is the same as x--;
Both the increment and decrement operators may either precede (prefix) or follow (postfix) the
operand. For example, x = x+1; can be written
++x; or x++;
There is, however, a difference between the prefix and postfix forms when you use these operators in
an expression. When an increment or decrement operator precedes its operand, the increment or
decrement operation is performed before obtaining the value of the operand for use in the expression.
If the operator follows its operand, the value of the operand is obtained before incrementing or
decrementing it.
For instance,
x = 10;
y = ++x; sets y to 11. However, if you write the code as
x = 10;
y = x++;
y is set to 10. Either way, x is set to 11; the difference is in when it happens. Most C/C++ compilers
produce very fast, efficient object code for increment and decrement operations code that is better
than that generated by using the equivalent assignment statement. For this reason, you should use the
increment and decrement operators when you can.
Here is the precedence of the arithmetic operators:
highest ++
(unary minus)
lowest +
Operators on the same level of precedence are evaluated by the compiler from left to right. Of course,
you can use parentheses to alter the order of evaluation. C/C++ treats parentheses in the same way as
virtually all other computer languages. Parentheses force an operation, or set of operations, to have a
higher level of precedence.
The following program contains the function xor( ), which returns the outcome of an exclusive OR
operation performed on its two arguments:
#include <stdio.h>
int xor(int a, int b);
int main(void)
{
printf("%d", xor(1, 0));
printf("%d", xor(1, 1));
printf("%d", xor(0, 1));
printf("%d", xor(0, 0));
return 0;
}
Variables
A variable is reserved memory location for storing some values.That means to tell the compiler
about storage of the variable with help of data-type.
the general syntax is,
for example,
C++ Identifiers
A C++ identifier is a name used for identifying any user defined things.That names refer a
variable, function, class, template, or any other custom-defined.Identifiers are sequences of
characters
Rules:
signed: -2147483648 to
2147483647
int Integer 4bytes
unsigned: 0 to
4294967295
signed: -2147483648 to
long int 2147483647
Long integer. 4bytes
(long) unsigned: 0 to
4294967295
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
Data Type Description Size Limit
Declaration Of Variables
In C++, all the variables must be declared before to use or initial statements of the block or
main or function or global. variables should specify with data type.
It binds a data type and an identifier with the variable. The data type allows the compiler to
execute statements correctly.
int a;
float number;
simple example program declares the variable, assign value and printing variable.
#include <iostream>
using namespace std;
int main ()
{
// declaring variables, Its name is b
int a;
// assining values in a:
a = 5;
#include <iostream>
using namespace std;
int main ()
{
// declaring variables , Its name are a,b and c
int a,b,c;
// assining values in a:
a = 5;
b = 10;
//Operating variables
c = a + b;
// just printing a result c
cout << c;
Introduction to strings
int main ()
{
// declaring variable str for string type
string str = "Hello C++ String";
Expression :
A combination of variables, constants and operators that represents a computation forms an
expression. Depending upon the type of operands involved in an expression or the result obtained
after evaluating expression, there are different categories of an expression. These categories of an
expression are discussed here.
Constant expressions: The expressions that comprise only constant values are called constant
expressions. Some examples of constant expressions are 20, a and 2/5+30 .
ns: The expressions that produce an integer value as output after performing all
types of conversions are called integral expressions. For example, x, 6*x-y and 10 +int (5.0) are
integral expressions. Here, x and yare variables of type into
ions: The expressions that produce floating-point value as output after performing
all types of conversions are called float expressions. For example, 9.25, x-y and 9+ float (7) are
The expressions that produce a bool type value, that is, either
true or false are called relational or Boolean expressions. For example, x + y<100, m + n==a-b
and a>=b + c .are relational expressions.
The expressions that produce a bool type value after combining two or more
relational expressions are called logical expressions. For example, x==5 &&m==5 and y>x I I
m<=n are logical expressions.
The expressions which manipulate data at bit level are called bitwise
expressions. For example, a >> 4 and b<< 2 are bitwise expressions.
Chained assignment: Chained assignment is an assignment expression in which the same value
is assigned to more than one variable, using a single statement. For example, consider these
statements.
a = (b=20); or a=b=20;
In these statements, value 20 is assigned to variable b and then to variable a. Note that variables
cannot be initialized at the time of declaration using chained assignment. For example, consider
these statements.
C++ Operators
Once we know of the existence of variables and constants, we can begin to operate with them.
For that purpose, C++ integrates operators. Unlike other languages whose operators are main
keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are
available in all keyboards. This makes C++ code shorter and more international, since it relies
less on English words, but requires a little of learning effort in the beginning.
You do not have to memorize all the content of this page. Most details are only provided to
serve as a later reference in case you need it.
Arithmetic Operator
Relational Operators
Syntax
Example :
a>b
Logical Operators
AND, OR operators are used when we want to use two or more Conditions.
If both the operations are successful, then the condition becomes true.
Logical And Operator Syntax
Assignment Operators
identifier = Expression
a=a+1 a+=1
a=a- 1 a-= 1
a=a*2 a*=2
a=a/2 a/= 2
a=a%2 a%=2
Advantages:
Unary Operators
There are two Unary Operators. They are Increment and Decrement.
Increment Unary Operator
variable++
++variable;
variable--;
--variable;
++i: increments l and then uses its value as the value of the expression;
i++: uses l as the value of the expression and then increments l;
--i: decrements l and then uses its value as the value of the expression;
i--: uses l as the value of the expression and then decrements l.
Change their original value.
Conditional or Ternary operator
Definition
Check condition if true, it returns first variable value otherwise return second values. sometimes
it replaces if..else statement
Syntax
Example
(a>10) ? b : c
Given that
a, b, c
are expressions;
the expression
(a>10) ? b : c
The Comma operator can be used to link the related expressions together.
While(c<10,c--)
The scope resolution operator is used for the Unary scope operator if a namespace scope (or)
Global Scope
Scope Resolution Operator Syntax
//simple syntax
:: global variable name
Definition
Syntax
data_type *ptr;
ptr = new data_type[size];
Definition
In C++, delete operator, is used to release memory or de-allocates memory that was
previously allocated by the new operator at runtime or end of the program.
Syntax
delete [] ptr;
Applications
The promising areas for application of OOP include:
Real-time systems
Simulation and modeling
Object oriented databases
Hypertext, hypermedia and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems.
for example, In c
if (i == 3) {
doSomething();
}
else {
doSomethingElse();
}
Syntax Explanation
which means the variable i contains a number that is equal to 3, the statements following the
doSomething() block will be executed.
Otherwise variable contains a number that is not equal to 3, else block doSomethingElse() will be
executed.
//Main Function
int main()
{
// Variable Declaration
int a;
{
// Block For Condition Success
else
{
// Block For Condition Fail
Sample Output:
This chapter will look at C's mechanisms for controlling looping and iteration. Even though some of
these mechanisms may look familiar and indeed will operate in a standard fashion most of the time.
for (expression1;Condition;expression2)
statement;
for (expression1;Condition;expression2) {
block of statements
expression1 initialises; expression2 is the terminate test; expression3 is the modifier (which may be more
than just simple increment);
NOTE: C/C++ basically treats for statements as while type loops
// Header Files
#include<iostream>
#include<conio.h>
//Main Function
int main()
{
// Variable Declaration
int x=3;
//for loop
for (x=3;x>0;x--)
{
cout<<"x="<<x<<endl;
}
Output:
x=3
x=2
x=1
The while statement is similar to those used in other languages although more can be done with the
expression statement -- a standard feature of C.
Syntax:
while (expression)
statement;
while (expression)
block of statements
// Header Files
#include<iostream>
#include<conio.h>
//Main Function
int main()
{
// Variable Declaration
int x=3;
//while loop
while (x>0)
{
cout<<"x="<<x<<endl;
x--;
}
getch();
Output:
x=3
x=2
x=1
Syntax:
}while (expression);
It is similar to PASCAL's repeat ... until except do while expression is true.
do while Loop example:
// Header Files
#include<iostream>
#include<conio.h>
//Main Function
int main()
{
// Variable Declaration
int x=3;
do {
cout<<"x="<<x<<endl;
x--;
}while (x>0);
return 0;
}
outputs:
x=3
x=2
x=1
NOTE: The postfix x- operator which uses the current value of x while printing and then decrements x.
C/C++ provides two commands to control how we loop: break and continue
Consider the following example where we read in integer values and process them according to the
following conditions. If the value we have read is negative, we wish to print an error message and
abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value
in the data. If the value is zero, we wish to terminate the loop.
In C/C++ programming language, the switch statement is a type of selection mechanism used to allow
block code among many alternatives.Simply, It changes the control flow of program execution via
multiple blocks.
case value2:
//Block 1 Code Here
break;
...
default:
// Header Files
#include<iostream>
#include<conio.h>
int main() {
// Variable Declaration
char ch;
switch (ch) {
case 'A': cout << "Your Character Is A\n";
break;
break;
break;
default: cout << "Your Character is Not Vowel.Otherwise Not a Capital Letter\n";
break;
}
// Wait For Output Screen
getch();
return 0;
}
Sample Output:
Your Character Is O
goto allows making an absolute jump to another point in the program. You should use this feature with
caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement. A
label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented programming
aside from those that low-level programming fans may find for it. For example, here is our countdown
loop using goto:
// Header Files
#include<iostream>
#include<conio.h>
//Main Function
int main() {
// Variable Declaration
int num = 10;
loop:
cout << num << ", ";
num--;
//goto usage
if (num > 0) goto loop;
getch();
Example programs
1. /* Divide the first number by the second. */
#include <stdio.h>
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
if(b) printf("%d\n", a/b);
else printf("Cannot divide by zero.\n");
return 0;
}
2. /* Count spaces */
#include <stdio.h>
int main(void)
{
char s[80], *str;
int space;
printf("Enter a string: ");
gets(s);
str = s;
for(space=0; *str; str++) {
if(*str != ' ') continue;
space++;
}
printf("%d spaces\n", space);
return 0;
}
3. loads a two-dimensional array with the numbers 1 through 12 and
prints them row by row.
#include <stdio.h>
int main(void)
{
int t, i, num[3][4];
for(t=0; t<3; ++t)
for(i=0; i<4; ++i)
num[t][i] = (t*4)+i+1;
/* now print them out */
for(t=0; t<3; ++t) {
for(i=0; i<4; ++i)
printf("%3d ", num[t][i]);
printf("\n");
}
return 0;
}
4. /* A very simple text editor. */
#include <stdio.h>
#define MAX 100
#define LEN 80
char text[MAX][LEN];
int main(void)
{
register int t, i, j;
printf("Enter an empty line to quit.\n");
for(t=0; t<MAX; t++) {
printf("%d: ", t);
gets(text[t]);
if(!*text[t]) break; /* quit on blank line */
}
for(i=0; i<t; i++) {
for(j=0; text[i][j]; j++) putchar(text[i][j]);
Object Oriented Programming with C++ 10CS36
Dept. of CSE, SJBIT 33
putchar('\n');
}
return 0;
}
5. Square and square root of a number
#include <stdio.h>
int sqr(int x);
int main(void)
{
int t=10;
printf("%d %d", sqr(t), t);
return 0;
}
int sqr(int x)
{
x = x*x;
return(x);
}
Reference and Bibliography
1.
2.
3.
4.
5.
6.