0% found this document useful (0 votes)
7 views

UNIT I

The document provides an overview of Object-Oriented Programming (OOP) principles, including concepts such as objects, classes, inheritance, polymorphism, and encapsulation. It discusses the benefits of OOP, applications, and the structure of C++ as an object-oriented language, including tokens, data types, and variable declarations. Additionally, it covers advanced topics like dynamic initialization, reference variables, and operators in C++.

Uploaded by

mukil.msc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT I

The document provides an overview of Object-Oriented Programming (OOP) principles, including concepts such as objects, classes, inheritance, polymorphism, and encapsulation. It discusses the benefits of OOP, applications, and the structure of C++ as an object-oriented language, including tokens, data types, and variable declarations. Additionally, it covers advanced topics like dynamic initialization, reference variables, and operators in C++.

Uploaded by

mukil.msc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

LOYOLA COLLEGE OF ARTS & SCIENCE, METTALA.

DEPARTMENT OF BCA

Staff Name: P. ASHOK Class: II BCA C Paper Code: 17UCA08

Paper Name : PROGRAMMING IN C++ Unit : I

OBJECT ORIENTED PROGRAMMING:

PRINCIPLES OF OBJECT ORIENTED PROGRAMMING:


Object oriented Programming (OOP) is an approach to program organization and
development that attempts to eliminate some of the pitfalls of conventional programming
methods by incorporating the best of structured programming features with several powerful
concepts.
It is defined as an approach that provides away of modularizing programs by creating
partitioned memory area for both data and functions that can be used as templates for creating
copies of such modules on demand.
An object is considered to be a partitioned area of computer memory that stores data and set of
operations that can access that data.
The concepts used extensively in object –oriented programming are
 Objects
 Classes
 Data abstraction
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
Objects:
Objects are the run-time entities in an object –oriented system. They may represent a person,
place, a bank account, a table of data or any item that the program has to handle.
When a program is executed, the objects interact by sending messages to one another. For
example if “customer’’ and “account’’ are two objects in a program, then the customer may
send a message to the account object requesting for the bank balance. Objects can interact
without having to know details of each other’s data or code. Objects contain code and data to
manipulate that data.
Classes:
The entire set of data and code of an object can be made a user defined data type with the help of
a 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 of similar type. For example, mango, apple, and orange are members
of class fruit. Classes are user defined data types and behave like the built in types of a
programming language
Fruit mango;
Will create an object mango belonging to the class fruit.

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

Flying bird Non flying bird

Robin Swallow Penguin kiwi


Polymorphism:
Polymorphism is another important OOP concept. Polymorphism means the ability to take
more than one form .An operation may exhibit different behavior 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 as operator
overloading.
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 call at runtime .It is associated with polymorphism and inheritance. It is
otherwise known as late binding.
Message Passing:

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.

OBJECT -ORIENTED LANGUAGES:


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
1. Object-based programming languages, and
2. Object-oriented programming languages
Object–based programming is the style of programming that primarily supports encapsulation
and object entity. Major features that are required for object based programming are:
 Data encapsulation

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:

Object-based features + inheritance + dynamic binding

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, EXPRESSIONS AND CONTROL STRUCTURES:


C++ is a superset of c and therefore most constructs of c are legal in C++ with their meaning
unchanged.

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.

IDENTIFIERS ANS CONSTANTS:


Identifiers refer to the names of variables, functions, arrays; classes, etc. create by the
programmer. They are the fundamental requirement of any language. Each language has its own
rules for naming these identifiers. The following rules are common to both C and C++ :
 Only alphabetic characters, digits and underscores are permitted
 The name cannot start with a digit

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.

BASIC DATA TYPES:


Data types in C++ can be classified as follows:

C++ Data types

User defined type Built-in type


Derived type
. Array
Structure Function
Union Pointer
Class reference
Enumeration

Void
Integral type Floating type

int char float double

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);

Another use of Void is in the declaration of pointers

5
Eg .Void *gp

USER –DEFINED DATA TYPES:

Structures and classes:


C ++ also permits us to define user-defined data type known as class which can be used ,just
like any other basic data type, to declare variables.
Enumerated Data Type:
An enumerated data type is another user-defined type which provides a way fro attaching
names to numbers.The enum keyword automatically enumerates a list of words by assigning them
values 0, 1, 2 and so on.
Enum shape {circle,square,triangle};
Enum colour{red,blue,green,yellow}

By using these tag names, we can declare new variables

Shape ellipse;
Colour background;

Eg: enum shape


{
circle;
rectangle;
triangle;
};
int main()
{
cout<< “ enter shape code :”;
int code;
cin>> code;
while(code >= circle && code<= triangle)
{
switch(code)
{
case circle:
………
………
break;
case rectangle:
………
………
break;
case triangle:
………
………
break;
}

6
cout << “ enter shape code:’;
cin >> code;
}
cout<< “BYE \n”;
}

DERIVED DATA TYPES :

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;
}

DYNAMIC INITIALIZATION OF VARIABLES:

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.

Eg: float average;


Average = sum/i;
Can be declared as Float average = sum/+ i

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

Data –type &reference name = variable-name

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:

:: Scope resolution operator


::* Pointer-to-member decalator
-> * Pointer-to-member operato
.* Pointer-to-member operato
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator

SCOPE RESOLUTION OPERATOR


C ++ is also a block structured language. Blocks and scopes can be used in constructing
programs. The scope of the variable extends from the point of declaration. A variable declare
inside a block is said to be local to that 43block.consider the following segment

……………
……………

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

This operator allows access to the global version of a variable.

MEMBER DEREFENCING OPERATORS:


C ++ permits us to define a class containing various types of data and functions as members. C
++ permits us to access the class members through pointers.
The member deferencing operators are given below
..* To declare a member of a class
* To access a member using object name and a pointer to that member
->* To access a member using a pointer to the object and a pointer to that member

MEMORY MANAGEMENT OPERATORS

C ++ supports malloc and calloc() functions to allocate memory dynamically


At run time. It also defines two unary operators new and delete that performs the task of
allocating and freeing the memory later in a better and easier way. Since these operators
manipulate memory on the free store, they are also known as free store operators.
A object can be created by using new, and destroyed by using delete, as and when required .A
data object created inside a block with new, will remain in existence until it is explicitly
destroyed by using delete. Thus, the lifetime of an object is directly under our control and it is
related to block structure of the program.

The new operator can be used to create objects of any type .It takes the following general form:

Pointer-Variable = new data type

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:

Pointer-Variable = =new data type (value)


new
Here value specifies the initial value.

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

Pointer-Variable = =new data type (size)

Eg.int *p =new int[10];

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:

Delete pointer- variable

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:

Delete[size] pointer- variable

The size specifies the number of elements in the array to be freed.


The new operator offers the following advantages over the function malloc()
1. It automatically computes the size of the data-object. We need not use the operator
sizeof.
2. It automatically returns the correct pointer type, so that there is no need to use a type
cast.

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”.

Eg.Cout << “m =” << m << endl


Cout << “n=” << n<< endl
Cout << “p =” << p << endl
If we assume the values of the variables 2597,14 and 175 the output will appear as follows

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)

Eg. Average = sum/(float) i ;


Average = sum/(float) i

C ++ also supports the following new cast operators:

 Const_cast
 Static_cast
 Dynamic_cast
 Reinterpret_cast.

EXPRESSIONS AND THEIR TYPES

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:

C ++ permits overloading of operators, thus allowing us to assign multiple meaning to


operators. The input /output operators << and >> are good examples of operator overloading.
This has been made possible by the header file iostream where a number of overloading
definitions are included.

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

->,( ), [ ],postfix + Left to right


+,postfix - - ,
prefix ++,prefix-
-,~ !

-> * * Right to left


* ,/,% Left to right
+- Left to right
<<,>> Left to right
<< =,>> = Left to right
==!= Left to right
& Left to right
^ 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:

There are three types of control structures:


1. Sequence structure(straight line)
2. Selection structure (Branching)
3. Loop structure (iteration)
The following figure illustrates this:

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;

The switch statement:


This is a multiple –branching statement where, based on a condition, the control transferred to
one of the many possible ways

Switch(Expression)
{
case 1:
{
Action 1;
}
case 2 :
{
Action 2;
}
case 3:
{
Action 3;
}
default :
{
Action 4;
}
}
action 5;

The do-While statement:

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:

while (condition is true );


{
action1;
}

action2;

The for statement:


The for statement is an entry controlled and is used when an action is to be repeated for a
predetermined number of times. The syntax is as follows:

For( initial value;test;increment)


{
action1;
}

action2;

18

You might also like