OOPS Note Lect-1 To 7
OOPS Note Lect-1 To 7
In the procedure oriented approach, the problem is viewed as the sequence of things to be done
such as reading, calculating and printing such as cobol, fortran and c. The primary focus is on
functions. A typical structure for procedural programming is shown in 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 for the
computer to follow, and organizing these instructions into groups known as functions. We
normally use flowcharts to organize these actions and represent the flow of control from one
action to another.
In a multi- function program, many important data items are placed as global 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 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 with the procedural approach is that we do not model real world
problems very well. This is because functions are action-oriented and do not really
corresponding to the element of the problem.
Object-oriented programming is the most recent concept among programming paradigms and
still means different things to different people.
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
1.3.1 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 term 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 one another. Foe
example, if “customer” and “account” are to object in a program, then the customer object may
send a message to the count object requesting for the bank balance. Each object contain data, and
code to manipulate data. Objects can interact without having to know details of each other’s data
or code. It is a sufficient to know the type of message accepted, and the type of response returned
by the objects. Although different author
represent them differently fig 1.5 shows two notations that are popularly used in object-oriented
analysis and design.
OBJECTS: STUDENT
DATA
Name
Date-of-birth
Marks
FUNCTIONS
Total
Average
Display
……..
1.3.2 Classes
We just mentioned that objects 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 class. In fact,
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 types. For examples, Mango,
Apple and orange members of class fruit. Classes are user-defined that types and behave like the
built-in types of a programming language. The syntax used to create an object is not different
then the syntax used to create an integer object in C. If fruit has been defines as a class, then the
statement
Fruit Mango;
The wrapping up of data and function into a single unit (called class) is known as encapsulation.
Data and encapsulation is the most striking feature of a class. The data is not accessible to the
outside world, and only those functions which are wrapped in the class can access it. These
functions provide the interface between the object’s data and the program. This insulation of the
data from direct access by the program is called data hiding or information hiding.
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 abstract
attributes such as size, wait, and cost, and function operate on these attributes. They encapsulate
all the essential properties of the object that are to be created.
The attributes are some time called data members because they hold information. The functions
that operate on these data are sometimes called methods or member function.
1.4.4 Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. For example, the bird,
‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived as illustrated in fig 1.6.
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 feature of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way that
it does not introduced any undesirable side-effects into the rest of classes.
1.4.5 Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior is 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 as
operator overloading.
Fig. 1.7 illustrates that a single function name can be used to handle different number and
different types of argument. This is something similar to a particular word having several
different meanings depending upon the context. Using a single function name to perform
different type of task is known as function overloading.
1.3.6 Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at run time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.
Consider the procedure “draw” in fig. 1.7. 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.
An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
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 results.
Message passing involves specifying the name of object, the name of the function
(message) and the information to be sent. Example:
Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
OOP offers several benefits to both the program designer and the user. Object-
Orientation contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises greater
programmer productivity, better quality of software and lesser maintenance cost. The
principal advantages are:
Simplicity: Software objects model real world objects, so the complexity is reduced and
the program structure is very clear.
Modularity: Each object forms a separate entity whose internal workings are decoupled
from other parts of the system.
Modifiability: It is easy to make minor changes in the data representation or the
procedures in an OO program. Changes inside a class do not affect any other part of a
program, since the only public interface that the external world has to a class is through
the use of methods.
Object-oriented programming is not the right of any particular languages. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially id designed to support the OOP concepts makes
it easier to implement them.
The languages should support several of the OOP concepts to claim that they are
object-oriented. Depending upon the features they support, they can be classified into the
following two categories:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading
Languages that support programming with objects are said to the objects-based
programming languages. They do not support inheritance and dynamic binding. Ada is a
typical object-based programming language.
Object-oriented programming language incorporates all of object-based
programming features along with two additional features, namely, inheritance and
dynamic binding. Object-oriented programming can therefore be characterized by the
following statements:
OOP has become one of the programming buzzwords today. There appears to be a great
deal of excitement and interest among software engineers in using OOP. Applications of
OOP are beginning to gain importance in many areas. The most popular application of
object-oriented programming, up to now, has been in the area of user interface design
such as window. Hundreds of windowing systems have been developed, using the OOP
techniques.
Real-business system are often much more complex and contain many more objects
with complicated attributes and method. OOP is useful in these types of application
because it can simplify a complex problem. The promising areas of application of OOP
include:
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
The object-oriented paradigm sprang from the language, has matured into design, and has
recently moved into analysis. It is believed that the richness of OOP environment will
enable the software industry to improve not only the quality of software system but also
its productivity. Object-oriented technology is certainly going to change the way the
software engineers think, analyze, design and implement future system.
C++ is a versatile language for handling very large programs; it is suitable for virtually
any programming task including development of editors, compilers, databases,
communication systems and any complex real life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special
object-oriented libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++
gives the language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs
to be implemented, it is very easy to add to the existing structure of an object.
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the
preprocessor. They are special lines interpreted before the compilation of the program itself begins. In
this case, the directive #include <iostream.h>, instructs the preprocessor to include a section of
standard C++ code, known as header iostream that allows to perform standard input and output
operations, such as writing the output of this program to the screen.
The function named main is a special function in all C++ programs; it is the function called when the
program is run. The execution of all C++ programs begins with the main function, regardless of where
the function is actually located within the code.
The open brace ({) indicates the beginning of main's function definition, and the closing brace (})
indicates its end.
The statement :
cout<< “Simple C++ program without using class”;
causes the string in quotation marks to be displayed on the screen. The identifier cout (pronounced as c
out) denotes an object. It points to the standard output device namely the console monitor. The operator
<< is called insertion operator. It directs the string on its right to the object on its left.
return 0;
This causes zero to be returned to the calling process (which is usually the operating system). Returning
zero indicates that the program terminated normally. Abnormal program termination should be signaled
by returning a nonzero value
int a; float b;
cin>>a>>b;
Output stream
It display contents of variables on the screen.
It uses insertion operation “ << ” before variable name. Syntax :
cout << variable; int a; float b; cout <<a << b;
1.9 BASIC DATA TYPES IN C++
Built-in-type
3. Integral type : – The data types in this type are int and char. The modifiers signed,
unsigned, long & short may be applied to character & integer basic data type. The size of int
is 2 bytes and char is 1 byte.
A generic pointer can be assigned a pointer value of any basic data type.
Ex . int *ip // this is int pointer
A void pointer cannot be directly assigned to their type pointers in c++ we need to use
cast operator.
Ex - void *ptr1;
char *ptr2;
3) Floating type:
The data types in this are float & double. The size of the float is 4 byte and double is 8 byte.
The modifier long can be applied to double & the size of long double is 10 byte.
• The user-defined data type structure and union are same as that of C.
• Classes – Class is a user defined data type which can be used just like any other
basic data type once declared. The class variables are known as objects.
• Enumeration
An enumerated data type is another user defined type which provides a way of attaching
names to numbers to increase simplicity of the code.
b) It uses enum keyword which automatically enumerates a list of words by assigning them
values 0, 1, 2,…..etc.
c) Syntax:-
enum shape {
Now shape becomes a new type name & we can declare new variables of this type.
Ex . shape oval;
d) In C++, enumerated data type has its own separate type. Therefore c++ does not
permit an int value to be automatically converted to an enum value.
Ex. shape shapes1 = triangle, // is allowed
shape shape1 = 2; // Error in c++
e) By default, enumerators are assigned integer values starting with 0, but we can over-
ride the default value by assigning some other value.
Ex enum colour {red, blue, pink = 3}; //it will assign red to o, blue to
1, & pink to 3 or enum colour {red = 5, blue, green}; //it will assign
red to 5, blue to 6 & green to 7.
Derived Data types:
1) Arrays
An array in c++ is similar to that in c, the only difference is the way character arrays are
initialized. In c++, the size should be one larger than the number of character in the string
where in c, it is exact same as the length of string constant.
2) Functions
Functions in c++ are different than in c there is lots of modification in functions in c++
due to object orientated concepts in c++.
3) Pointers
c++ adds the concept of constant pointer & pointer to a constant pointer.
char const *p2 = .HELLO.; // constant pointer
Next you have a summary of the basic fundamental data types in C++, as well as the range
of values that can be represented with each one
Declaration of variables.
C requires all the variables to be defined at the beginning of a scope. But c++ allows the
declaration of variable anywhere in the scope. That means a variable can be declared right
at the place of its first use. It makes the program easier to understand. In order to use a
variable in C++, we must first declare it specifying which data type we want it to be. The
syntax to declare a new variable is to write the specifier of the desired data type (like int,
bool, float...) followed by a valid variable identifier. Ex.: int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable of type int
with the identifier a. The second one declares a variable of type float with the identifier
mynumber. Once declared, the variables a and mynumber can be used within the rest of
their scope in the program. If you are going to declare more than one variable of the
same type, you can declare all of them in a single statement by separating their
Ex.: int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly the
same meaning as: int a; int b; int c;
The integer data types can be char, short, long. Integer data type can be either signed or
unsigned depending on the range of numbers needed to be represented. Signed types can
represent both positive and negative values, whereas unsigned types can only represent
positive values (and zero). This can be specified by using either the specifier signed or the
specifier unsigned before the type name. Ex.: unsigned short int Number;
By default, if we do not specify either signed or unsigned most compiler settings will
assume the type to be signed, therefore instead of the second declaration above we
int Balance;
with exactly the same meaning (with or without the keyword signed). An exception to this
general rule is the char type, which exists by itself and is considered a different fundamental
data type from signed char and unsigned char, thought to store characters. You should use
either signed or unsigned if you intend to store numerical values in a char-sized variable.
short and long can be used alone as type specifiers. In this case, they refer to their
respective integer fundamental types: short is equivalent to short int and long is equivalent
to long int. The following two variable declarations are equivalent: short Year; short int Year;
Scope of variables:
All the variables that we intend to use in a program must have been declared with its type
specifier in an earlier point in the code, like we did in the previous code at the beginning of
the body of the function main when we declared that a, b, and result were of type int. A
variable can be either of global or local scope. A global variable is a variable declared in the
main body of the source code, outside all functions, while a local variable is one declared
within the body of a function or a block. Global variables can be referred from anywhere in
the code, even inside functions, whenever it is after its declaration. The scope of local
variables is limited to the block enclosed in braces ({ })
where they are declared. For example, if they are declared at the beginning of the body of a
function (like in function main) their scope is between its declaration point and the end of
that function. In the example above, this means that if another function existed in addition to
main, the local variables declared in main could not be accessed from the other function
and vice versa.
In c++, a variable can be initialized at run time using expressions at the place of declaration.
This is referred to as dynamic initialization. Ex int m = 10;
Reference variables
If we make the variable sum a reference to the variable total, then sum & total can be
used interchangeably to represent that variable.
iii) Reference variable is created as:- data type &reference name = variable name;
Ex int sum = 200; int &total = sum;
Here total is the alternative name declared to represent the variable sum. Both variable efer
to the same data object in memory.
int main( ) {
int n = 10;
}
When the function call fun(n) is executed, it will assign x to n i.e. int &x = n;
Therefore x and n are aliases & when function increments x. n is also incremented. This
type of function call is called call by reference.
Introduction to strings:
Variables that can store non-numerical values that are longer than one single character are
known as strings. The C++ language library provides support for strings through the
standard string class. This is not a fundamental type, but it behaves in a similar way as
fundamental types do in its most basic usage. A first difference with fundamental data types
is that in order to declare and use objects (variables) of this type we need to include an
additional header file in our source code: <string> and have access to the std namespace
(which we already had in all our previous programs thanks to the using namespace
statement).The following initialization formats are valid for strings:
string mystring = “This is a string”;
string mystring (“This is a string”);
Strings can also perform all the other basic operations that fundamental data types can, like
being declared without an initial value and being assigned values during execution.
This statement assigns the integer value 5 to the variable a. The part at the left of the
assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue
(right value). The lvalue has to be a variable whereas the rvalue can be a constant, a
variable, the result of an operation or any combination of these. The most important rule
when assigning is the right-to-left rule: The assignment operation always takes place from
right to left, and never the other way: a= b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the
rvalue). The value that was stored until this moment in a is not considered at all in this
operation, and in fact that value is lost.
Arithmetic operators ( +, -, *, /, % )
+ addition
- subtraction
* multiplication /
division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their
respective mathematical operators. The only one that you might not be so used to see may
be modulo; whose operator is the percentage sign (%). Modulo is the operation that gives
the remainder of a division of two values. For example, if we write:
a = 11 %3;
The variable a will contain the value 2, since 2 is the remainder from dividing 11
between 3.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators: expression
is equivalent to
a /= b; a = a / b;
Shortening even more some expressions, the increase operator (++) and the decrease
operator (--) increase or reduce by one the value stored in a variable. They are equivalent to
+=1 and to -=1, respectively. Thus:
are all equivalent in its functionality: the three of them increase by one the value of c.
A characteristic of this operator is that it can be used both as a prefix and as a suffix. That
means that it can be written either before the variable identifier (++a) or after it (a++).
Although in simple expressions like a++ or ++a both have exactly the same meaning, in
other expressions in which the result of the increase or decrease operation is evaluated as
a value in an outer expression they may have an important difference in their meaning: In
the case that the increase operator is used as a prefix (++a) the value is increased before
the result of the expression is evaluated and therefore the increased value is considered in
the outer expression; in case that it is used as a suffix (a++) the value stored in a is
increased after being evaluated and therefore the value stored before the increase
operation is evaluated in the outer expression.
Relational and equality operators ( ==, !=, >, <, >=, <= ):
In order to evaluate a comparison between two expressions we can use the relational
and equality operators. The result of a relational operation is a Boolean value that can
only be true or false, according to its Boolean result.
We may want to compare two expressions, for example, to know if they are equal or if one
is greater than the other is. Here is a list of the relational and equality operators that can be
used in C++:
Operators Meaning
== Equal to
!= Not equal to
(3 != 2) // evaluates to true. (6
>= 6) // evaluates to true. (5 < 5)
// evaluates to false.
Of course, instead of using only numeric constants, we can use any valid expression,
including variables. Suppose that a=2, b=3 and c=6,
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
Be careful! The operator = (one equal sign) is not the same as the operator == (two equal
signs), the first one is an assignment operator (assigns the value at its right to the variable
at its left) and the other one (==) is the equality operator that compares whether both
expressions in the two sides of it are equal to each other.
Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we
compared it to a, that also stores the value 2, so the result of the operation is true.
The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one
operand, located at its right, and the only thing that it does is to inverse the value of it,
producing false if its operand is true and true if its operand is false. Basically, it returns the
opposite Boolean value of evaluating its operand.
For example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6
<= 4) // evaluates to true because (6 <= 4) would be false.
The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds with Boolean logical operation AND. This
operation results true if both its two operands are true, and false otherwise. The following
panel shows the result of operator && evaluating the expression a && b:
&& OPERATOR a
b a && b true true
true true false false
false true false
false false false
This operation results true if either one of its two operands is true, thus being false only
when both operands are false themselves. Here are the possible results of a || b:
|| OPERATOR
a b a || b
The conditional operator evaluates an expression returning a value if that expression is true
and a different one if the expression is evaluated as false. Its format is: condition ? result1 :
result2
If condition is true the expression will return result1, if it is not it will return result2.
Comma operator ( , ):
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be
evaluated for a value, only the rightmost expression is considered. For example, the
following code:
a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
sizeof()
This operator accepts one parameter, which can be either atype or a variable itself and
returns the size in bytes of that type or object: a = sizeof (char);
This will assign the value 1 to a, because char is a one-byte long type. The value returned
by sizeof is a constant, so it is always determined before program execution.
Some of the new operators in c++ are-
1) C++ is a block - structured language. The scope of the variable extends from the point of
its declaration till the end of the block containing the declaration.
2) Consider following program.
...
....
{
int x = 1;
===
}
=====
{
int x = 2;
} =====
The two declaration of x refer to two different memory locations containing different values.
Blocks in c++ are often nested. Declaration in a inner block hides a declaration of the same
3) In C, the global version of a variable cannot be accessed from within the inner block.
C++ resolves this problem by using scope resolution operator (::), because this operator
allows access to the global version of a variable.
# include<iostream.h >
{
int m = 10;
int main ( ) {int m = 20; {int k = m; int m = 30;
cout << .K = . <<k; cout << .m = .<<m; cout << : : m = . << : : m;
}
cout << .m. = .<< m;
cout << .::m = <<::m;
return 0;
In the above program m is declared at three places. And ::m will always refer to global m.
5) A major application of the scope resolution operator is in the classes to identify the class
to which a member functions belongs.
C++ permits us to define a class containing various types of data & functions as members.
C++ also permits us to access the class members through pointers. C++ provides a set of
three pointer. C++ provides a set of three pointers to member operators.
3) * - To access a member using a pointer in the object & a pointer to the member.
1) We use dynamic allocation techniques when it is not known in advance how much of
memory space is needed. C++ supports two unary operators new and delete that perform
the task of allocating & freeing the memory.
2) An object can be created by using new and destroyed by using delete. A data object
created inside a block with new, will remain existence until it is explicitly destroyed by using
delete.
3) It takes following form.
variable = new data type
The new operator allocated sufficient memory to hold a data object of type data-type &
returns the address of the object.
EX p = new int.
Where p is a pointer of type int. Here p must have already been declared as pointer of
appropriate types.
4) New can be used to create a memory space for any data type including user defined
type such all array, classes etc.
Ex int * p = new int [10]; Creates a memory space for an array of 10 integers.
5) When a data object is no longer needed, it is destroyed to release the memory space for
reuse. The general form is delete variable. If we want to free a dynamically allocated array,
we must use following form.
delete [size] variable; The size specifies the no of elements in the array to be freed.
i) It automatically computes the size of the data object. No need to use sizeOf()
ii) If automatically returns the correct pointer type, so that there is no need to use a type
cast.
iii) new and delete operators can be overloaded.
iv) It is possible to initialize the object while creating the memory space.
Manipulators:
Manipulators are operators that are used to format the data display. There are two
important manipulators.
1) endl
2) stew
1) endl : -
This manipulator is used to insert a linefeed into an output. It has same effect as using
.\n. for newline.
Ex cout<< .a. << a << endl <<.n=. <<n; << endl<<.p=.<<p<<endl;
The output is a = 2568
n = 34 p = 275 2)
Setw : -
With the stew, we can specify a common field width for all the numbers and force them to
print with right alignment.
The manipulator setw(5) specifies a field width of 5 for printing the value of variable sum
the value is right justified.
356