UNIT I
UNIT I
DEPARTMENT OF BCA
1
Data Abstraction and Encapsulation:
The wrapping up of data and functions into a single unit is known as Encapsulation. The
data is not accessible to the outside world, and only to those functions, which are
wrapped in the class, can access it. These functions provide a 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 explanations. They encapsulate all the essential properties of the
objects that are to be created. These attributes are sometimes called data members
because they hold information. The functions that operate on these data are sometimes
called methods or member functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Type(ADT).
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects
of another class .It supports the concept of hierarchical classification. For example, the
bird ‘robin’ is a part of the class ‘flying bird’, which is again a part of the class bird.
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 combine features
of both the classes.
Bird
2
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 way
people pass messages to one another. Message Passing involves specifying the name of the
object, the name of the function (message) and information to be sent. Example:
Employee. Salary(name)
Object Information
Message
Objects have a life cycle. They can be created and destroyed. Communication with an object is
possible as long as it is alive.
BENEFITS OF OOP:
OOP offers several benefits to both the designer and the user. Object orientation contributes to
the solution of many problems associated with the development and quality of software products.
Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
We can build programs from the standard working modules that communicate with one
another.
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
The data –centered design approach enables us to capture more details of a model in
implement able form
Object oriented designs 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.
3
Data hiding and access mechanism
Automatic initialization and clear- up of objects
Operator overloading
Object –oriented programming 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 statement:
APPLICATIONS OF OOP:
Applications of OOP are beginning to gain importance in many areas. The most popular
application of object oriented programming is in the area of user interface design .The promising
areas of OOP include :
Real-time systems
Simulation and modeling
Object oriented database
Hypertext, Hypermedia and expertext`
AI and expert system
Neural Networks and parallel programming
Decision support and parallel programming
CIM/CAM/CAD systems
TOKENS:
The smallest individual units in a program are known as tokens.C++ has the following tokens :
Keywords
Identifiers
Constants
Strings
Operators
KEYWORDS:
The keywords implement specific C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user defined elements.
Given below are some of the keywords:
Private,do,protected,static,struct,volatile,while,virtual,void,friend,for,extern
Auto,else,enum, etc.
4
Uppercase and lowercase letters are distinct
A declared keyword cannot be used as a variable name
A major difference between C and C++ is the limit on the length of a name. While C recognizes
only the first 32 characters in a name C++ places no limit on its length
Constants refer to fixed values that do not change during the execution of a program. C++
supports several kinds of literal constants. They include integers, characters; floating point
numbers and strings. They don’t have memory locations.
Eg : 123 – decimal integer
12.34 - floating point integer
037 - Octal integer
0x2 – hexadecimal integer
“C++”- string constant
‘A’ –character constant
C++ also supports backslash character constants such as’/a’,’/n’,’/t’. etc as in the case of C.
Void
Integral type Floating type
C++ compilers support all the built in data types. they are also known as basic or fundamental
data types .The modifiers signed, unsigned ,long, short may be applied to character and integer
basic data types. The modifier long may also apply to double.
The type Void was introduced in C. Two normal uses of void are (1) to specify the return type
of a function when it is not returning any value, and (2) to indicate an empty argument list to a
function
Eg. Void funct1 (void);
5
Eg .Void *gp
Shape ellipse;
Colour background;
6
cout << “ enter shape code:’;
cin >> code;
}
cout<< “BYE \n”;
}
Arrays:
The application of arrays in C++ is similar to that in C. When initializing a character array
in C, the complier will allow us to declare the array size as the exact length of the string constant
Char string [3] = “xyz”;
But in C++, the size should be one larger than the number of characters in the string.
Char string [4] =”xyz”
Functions:
Functions have undergone major changes in C++. While some of the changes are simple, others
require a new way of thinking when organizing our programs. Many of the modifications and
improvements were driven by the requirements of the object oriented concept of C++
Pointers:
Pointers are declared and initialized as in C
Int *ip;
ip =&x;
*ip = 10;
C ++ adds the concept of constant pointer and pointer to a constant
Char * const ptr1 =”GOOD”;
SYMBOLIC CONSTANTS:
There are two ways of creating symbolic constants in C++
Using the qualifier Const, and
Defining a set of integer constants using enum keyword
In C++, we can use const in a constant expression, such as
Const int size = 10;
Char name [size];
A const in C++ defaults to the internal linkage and therefore it is local to the file where it is
declared. To give a const value an external linkage so that it can be referenced from, another file,
we must explicitly define it as an Extern in C++
Extern const total= 100;
Another method of naming integer constants is by enumeration as under
Enum {x,y,z}
This defines X, Y, Z as integer constants with values 0, 1, and 2 respectively, this is equivalent
to:
Const x = 0;
Const y =1;
Const z = 2;
7
TYPE COMPABILITY:
C ++ defines int, short int and long int as three different types. They must be cast when their
values are assigned to one another. Similarly, unsigned char char and signed char are considered
as different types, although each has assize of one byte.
These restrictions in C++ are necessary to support function overloading when two functions with
the same are distinguished using the type of function arguments.
DECLARATION OF VARIABLES:
C++ allows the declaration of a variable anywhere in the scope. This means that a variable can
be declared right at the place of its first use. This makes the program much easier to write and
reduce errors that may be caused by having to scan back to forth. It also makes the program
easier to understand because the variables are declared in the context of their use.
Eg: int main ()
{
float x;
float sum = 0;
for( int i =1;I<5; I++)
{
cin>> x;
sum =sum + x;
}
float average;
average = sum/(I-1);
cout<< average;
return 0;
}
C++, however, permits initialization of the variables at run time. This is referred to as dynamic
initialization .In C++, a variable can be initialized at run time using expressions at the place of
declaration.
REFERENCE VARIABLES:
C++ introduces a new kind of variable known as the reference variable. A reference variable
provides an alternative name for a previously defined variable.
A reference variable is created as follows
Eg:
Float total = 100;
8
Float&sum= total;
total is afloat type variable already declared; sum is the alternative name declared to represent
the variable total.
The statements
cout<< total; and
cout<< sum;
Will print the value 100.
A reference variable must be initialized at the time of declaration. This establishes the
correspondence between the reference and the data object which it names.
A major pplication fo reference variable is passing arguments to functions.
Eg.
Void f(int & x)
{
x = x + 10;
}
int main( )
{
int m = 10;
f(m);
……
……
}
when the function call f(m) is executed, the following initialization occurs :
int & x =m;
Thus x becomes an alternate of m after executing the statement
f(m);
OPERATORS IN C ++
C ++ has a rich set of operators. These are given below:
……………
……………
9
{
int x = 10;
………
………
}
……….
……….
{
int x = 1;
………..
………..
}
The two declarations of x refer to two different memory locations containing different values.
Statements in the second block cannot refer to the variable x declared in the first block and vice
versa
C ++ resolves this problem by introducing a new operator:: called the scope resolution operator.
This can be used to uncover a hidden variable. It takes the following form:
: : Variable-name
The new operator can be used to create objects of any type .It takes the following general form:
10
The new operator allocates sufficient memory to hold a data object of type data-type and
returns the address of the object. The data- type may be any valid data type. The pointer variable
holds the address of the memory space allocated.
P= new int;
q = new float;
Where p is a pointer of type int and q is a pointer of type float.
We can also initialize the memory using the new operator. This is done as follows:
New can be used to create a memory space for any data type such as arrays, structures and
classes.
The general form for one –dimensional array is
When a data object is no longer needed, It is destroyed to release the memory space for reuse.
The general form of its use is:
The pointer –variable is the pointer that points to a data object created with New.
Eg. Delete P;
Delete q;
If we want to free a dynamically allocated array, We must use the following form
Delete:
11
3. It is possible to initialize the object while creating the memory space.
4. Like any other operator new and delete can be overloaded.
MANIPULATORS:
Manipulators are operators that are used to format the data display. The most commonly
used operators are endl and setw
The endl manipulator, when used in an output statement causes a linefeed to be inserted. It
has the same effect as using the newline character “\n”.
M=
2 5 9 7
N= 1 4
P= 1 7 5
The mainpualtor setw (5) specifies a field width for printing the value of the variable sum.
3 4 5
TYPECAST OPERATOR:
C++ permits explicit type conversion of variables or expressions using the type cast operator.
The following two versions are equivalent
(type-name) expression
type-name (expression)
Const_cast
Static_cast
Dynamic_cast
Reinterpret_cast.
An expression is a combination of operators, constants and variables arranged as per the rules of
the language. It may also include function call which returns values .An expression may consist
of one or more operands and zero or more operators to produce a value .Expressions may one of
the following seven types
Constant expressions
12
Integral expressions
Float expressions
Pointer expressions
Relational expressions
Logical expressions
Bitwise expressions
Constant expressions:
Constant expressions consist of only constant valus.
Eg 15 , 20 + 5 / 2.0 ,’x’
Integral expressions:
Intregral expressions are those which produce integer results after implementing all the
automatic and explicit type conversions.
E. m,m*n-5,m*’x’
Where m and n integers
Float expressions:
Float expressions are those which, after all conversions produce floating point results
Eg.X+Y,5+Float (10)
Where X and Y are floating point variables
Pointer Expressions
Pointer expressions produce address values
Eg. &m,ptr
Wher m= is a variable and ptr is a pointer
Relational Expressions
Relational expressions yield results of type Bool which takes a value true or false
Eg.X <= y
a+b = = c +d
When arithmetic expressions are used on either side of a relational operator, they will be
evaluated first and then the results are compared. Relational expressions are also known as
Boolean expressions,
Logical Expressions:
Logical expression combines two or more relational expressions and produces BOOL
Results.
Eg: a > b && x = =10
Bitwise Expressions:
Bitwise expressions are used to manipulate data at bit level. They are basically used for testing or
shifting bits
X << 3; Shifts three bit positions to left
Y >> 1;Shifts one bit position to right;
SPECIAL ASSIGNMENT OPERATOR:
There are three type of assignment operators:
1) Chained assignment :
X = ( y = 10)
First the value is assigned to x then to y.
A chained assignment cannot be used to initialize variables at the time of declaration.
2) Embedded assignment:
13
X = ( y= 50) + 10;
Here, the value 50 is assigned to y and then the result is assigned to x.This statement is
identical to
Y = 50;
X = y +10;
3) Compound assignment:
C ++ supports a compound assignment operator which is a combination of the assignment
operator with a binary operator. For example
X = X + 10;
May be written as
X += 10;
The operator += is known as assignment operator or short hand assignment operator.
The general form is
Variable1 op = variable 2;
Where op is a binary operator
IMPLICIT CONVERSION:
Wherever data type’s art mixed in an expression, C++ performs the conversions
automatically. This process is known as implicit or automatic conversion.
OPERATOR OVERLOADING:
OPERATOR PRECEDENCE:
C ++ enables us yo add multiple meanings to the operators, yet their association and
precedence remain the same.
Operator Associativity
:: Left to right
14
| Left to right
&& Left to right
|| Left to right
?: Left to right
=* ,= /, =%, =+,= = Left to right
<< =,>> =,&=,^= ,| Right to left
=
, Left to right
CONTROL STRUCTURES:
ACTION 1
Entry
ACTION 2
ACTION 3
EXIT
(a) Sequence
Entry
True false
Conditi
on
15
Action 1 Action 2
Exit
Action 3
(b) selection
Entry
Loop
True
Conditio Action 1
n
False
Action 2
( c ) Loop.
The If statement:
The If statement is implemented in two forms :
Simple if statement
If …else statement
16
Form 1
If ( expression is true)
{
action1;
}
}
action2;
action3;
Form2 :
If ( expression is true )
{
Action 1;
}
else
{
action 2;
}
action3;
Switch(Expression)
{
case 1:
{
Action 1;
}
case 2 :
{
Action 2;
}
case 3:
{
Action 3;
}
default :
{
Action 4;
}
}
action 5;
17
The do-While is an exit-controlled loop. Based on condition, the control is transferred back to
the particular point in the program. The syntax is as follows:
Do
{
action1;
}
while (condition is true );
action2;
While statement :
This is also a loop structure, but is an entry-controlled one. The syntax is as follows:
action2;
action2;
18