0% found this document useful (0 votes)
8 views40 pages

Unit 1 Notes

Uploaded by

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

Unit 1 Notes

Uploaded by

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

2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

UNIT I

Introduction to OOPS

object-Oriented Programming - Features of C++ - I/O Operations, Data Types, Variables-


Static, Constants-Pointers-Type Conversions – Conditional and looping statements – Arrays -
C++ 11 features - Class and Objects, Abstraction and Encapsulation, Access Specifiers,
Methods- UML Diagrams Introduction – Use Case Diagram - Class Diagram.

======================================================================

WHY OBJECT-ORIENTED PROGRAMMING IN C++:


From the history of computer programming most programs were written procedurally.
Procedural programs consist of a series of steps or procedures that take place one after the other.
The programmer determines the exact conditions under which a procedure takes place, how often
it takes place, and when the program stops.
Programmers write procedural programs in many programming languages, such as COBOL,
BASIC, FORTRAN etc. Over the years, as programmers have better ways to accommodate the way
people work best on computers, procedural programming techniques have evolved into object-
oriented techniques.
Programming in the oldest procedural languages had two major disadvantages:
• The programming process involved with so much detail.
• Similar statements required in various parts of the program had to be rewritten in more
than one place.
So in order to overcome this programmers use the concept of methods. It contains groups
of statements that can be executed as a unit. Methods allows programmers to group statements
together into modules, which are known in various programming languages as functions,
procedures, methods, subprograms, subroutines, or simply routines. Dividing the big program into
small modules to work with is called as Modular Programming. Modular programs are easier to
work than non-modular ones.
The concept of methods leads to Abstraction. It is the process of paying attention to
important properties while ignoring details. For example, talking on the telephone without
considering how the signals are transmitted. With the advantage of abstraction, modular programs
can be written more quickly because different programmers can be assigned to write different
modules. If the program contains four modules, four programmers can work simultaneously (at
the same time), with each handling one-fourth of the job. An additional advantage to
modularization is that a well-written module may be called from multiple places within the same
program or from another program.
With abstraction the variables and instructions within a module are hidden and contained
leads to Encapsulation. It helps to make the module independent of all other modules and
therefore reusable.
Object-oriented programs use all the features of procedural programs and require a
different way of thinking and add several new concepts to programming:

Page No: 1
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

• Analyze the objects with which we are working - both the attributes of those objects and
the tasks that need to be performed on those objects.
• Messages can be passed to objects, requesting the objects to take action.
• The same message works differently when applied to the various objects.
• A method can work appropriately with different types of data it receives, without the need
for separate method names.
• Objects can inherit features of previously created objects, thereby reducing the time it
takes to create new objects.
• Information hiding is more complete than in procedural programs.
============================================================================
OBJECT ORIENTED PROGRAMMING CONCEPTS

The basic principles behind using object-oriented programming techniques are as follows:

• Objects
• Classes
• Data Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• Message Passing
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. 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
object may send a message to the account object requesting for the bank balance. Each object
contains data, and code to manipulate the data. Objects can interact without having to know details
of each other's data or code. It is sufficient to know the type of message accepted, and the type of
response returned by the objects.

Classes:

A class is thus a collection of objects of 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. If fruit has been defined as a class, then the statement: Fruit
mango; will create an object mango belonging to the class Fruit.

Data Encapsulation:

Page No: 2
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data 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.

Data Abstraction

Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a list
of abstract attributes such as size, weight and cost, and functions to operate on these attributes.
They encapsulate all the essential properties of the objects that are to be created. The 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 Types (ADT). The technique of creating new
data types that are well suited to an application to be programmed is known as data abstraction.
The class is a construct in C++ for creating user-defined data types called ADT’s.

Inheritance:

Inheritance is the process of deriving one class into another class by inheriting all the
properties of the base class. In OOP, the concept of inheritance provides the idea of reusability and
supports the concept of hierarchical classification. This means that we can add additional features
to an existing class without modifying it.

Example, the class ‘Square’ is a part of the class '2DimensionalShapes' which is again a part
of the class 'Shape'. The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived as illustrated below,

Polymorphism:

• Polymorphism means the ability to take more than one form.

• In that “Poly” means many and “Morphism” means taking more than one form. Basically it
is an Greek word.

• It allows a single name/operator to be associated with different operations depending on


the type of data passed on it.

Page No: 3
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

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

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 object, the name of the function (message) and the information to be
sent. Example:

Objects have a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.

============================================================================

INTRODUCTION TO C++

C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at


AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980's. Stroustrup, an admirer
of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and
create a more powerful language that could support object-oriented programming features and
still retain the power and elegance of C. The result was C++. Therefore, C++ is an extension of C.
C++ is a superset of C.

The most important facilities that C++ adds on to C are classes, inheritance, and function
overloading, and operator overloading. The object-oriented features in C++ allow programmers to
build large programs with clarity, extensibility and ease of maintenance, incorporating the spirit
and efficiency of C.

Applications of C++:

Page No: 4
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

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 application systems.

• Since C++ allows 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 close 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.

• It is expected that C++ will replace C as a general-purpose language in the near future.

Comments

C++ introduces a new comment symbol // (double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. Note that there is no closing symbol. The double
slash comment is basically a single line comment.

// This is an example of C++ program to illustrate some of its features.

Multiline comments can be written as follows:

The C comment symbols /*, */are still valid and are more suitable for multiline comments.

/* This is an example of C++ program

to illustrate some of its features */

Output Operator: ( << )

The statement: cout <<”Sum = “<< x+y+z;

The operator << is known as “insertion” or “put to” operator. It inserts (or puts) the
value to the output screen. This corresponds to the familiar printf( ) operation in C.

Input Operator: ( >> )

The statement: cin >> number 1;

is an input statement and causes the program to wait for the user to type in a number. The number
keyed in is placed in the variable number l. The identifier cin (pronounced 'C in') is a predefined
object in C++ that corresponds to the standard input stream. Here, this stream represents the
keyboard.

The operator >> is known as extraction or get from operator. It extracts (or takes) the
value from the keyboard and assigns it to the variable on its right. This corresponds to the familiar
scanf( ) operation in C.

============================================================================

Page No: 5
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

BASIC DATATYPES/ NATIVE TYPES:

Data types are used to indicate a specific value. When programming, we store the variables
in our computer's memory, but the computer has to know what kind of data we want to store in
them, since it is not going to occupy the same amount of memory to store a simple number than to
store a single letter or a large number, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte can store a relatively small amount of data: one single
character or a small integer (generally an integer between 0 and 255). In addition, the computer
can manipulate more complex data types that come from grouping several bytes, such as long
numbers or non-integer numbers. Data types in c++ can be of seven basic C++ data types.
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers:
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store the value
in memory, and what is maximum and minimum value which can be stored in such type of
variables.
Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767

Page No: 6
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

long int 4bytes -2,147,483,647 to 2,147,483,647


signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character
Following is the example, which will produce correct size of various data types on your computer.
using namespace std;
#include <iostream>
main( )
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
}
Output:
Size of char : 1
Size of short int : 2
Size of float : 4
Size of double : 8
Size of wchar_t : 4

This example uses endl, which inserts a new-line character after every line and
sizeof() function to get size of various data types.
typedef Declarations:
New name for an existing type can be created using typedef. Following is the simple syntax
to define a new type using typedef:
typedef Datatype variableName;
For example, the following tells the compiler that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called distance:
feet f1,f2;
Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more identifiers
that can be used as values of the type. Each enumerator is a constant whose type is the
enumeration. To create an enumeration requires the use of the keyword enum. The general form
of an enumeration type is:

Page No: 7
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

enum enumName {list of names} Variable;

Where,
• The enum is an Keyword.
• enum-name is the enumeration's type name.
• The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the
variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue} c;
c=blue;
By default, the value of the first name is 0, the second name has the value 1, the third has
the value 2, and so on. But we can give a name a specific value by adding an initializer. For example,
in the following enumeration, green will have the value 5.
enum color { red, green=5, blue} c;
c=blue;
Here, blue will have a value of 6 because each name will be one greater than the one that precedes
it.
============================================================================
Tokens:

The smallest individual units in a program are known as tokens. C++ has the following
tokens:
• Keywords
• Identifiers
• Constants
• Operators
• Strings
(a) Keywords:

They are explicitly reserved identifiers and cannot be used as names for the program
variables or other user-defined program elements.

(b) Identifiers

Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programmer. They are the fundamental requirement of any language. Each language has its own
rules for naming these identifiers. The rules for declaring an identifier are as follows:
• Identifier name must start with alphabetic characters, digits or underscore.
• Identifier name cannot start with a digit.
• Uppercase and lowercase letters are treated as different.
• Keywords should not be used as an identifier.
• No space must be present between the identifier name.
(c) Constants

Page No: 8
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Constants are expressions with a fixed value. Constants can be divided into Integer
Constants, Floating-Point Constants, Character Constants, String Constants and Boolean Values.
(i) Integer Numerals are numerical constants that identify integer decimal values.
Example: 1776, 707, -273
In addition to decimal numbers C++ allows the use as Integer constants of octal numbers
(base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to
precede it with a 0 (zero character). And in order to express a hexadecimal number we have to
precede it with the characters 0x (zero, x). For example, the following literal constants are all
equivalent to each other:

75 // decimal
0113 // octal
0x4b // hexadecimal

(ii) Floating Point Constants are numbers with decimals and/or exponents. They can include
either a decimal point, an e character or both a decimal point and an e character.
Example:

3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0

(iii) Character Constants - Character Constants are enclosed within single quotes ( ‘ ‘ )
Example: 'z', ‘&’, ‘G’
(iv) String Constants - String Constants are enclosed within double quotes ( “ “ )
Example: “Hello”, “EEE Depart”

Escape codes/Escape Sequence - These are special characters that are difficult or impossible to
express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are
preceded by a backslash (\). Some of the escape codes:

\n newline
\r carriage return
\t Tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
(v) Boolean literals - There are only two valid Boolean values: true and false. These can be
expressed in C++ as values of type bool by using the Boolean literals true and false.

Page No: 9
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Declared constants (const)


With the const prefix we can declare constants with a specific type in the same way as
variables aredeclared.
Example: const float PI=3.14;
Here, “PI” is an typed constants. It was used like regular variables except it value cannot be
modified after the definition.
Variables:

In order to store the value variable is needed. All variables must be declared before they
may be used in the program.

Syntax: Datatype Variable Name1,Variable Name2, ….., Variable NameN;

The following statement uses four variables numberl, number2, sum, and average. They are
declared with datatype float.

float number 1, number 2, sum, and average;

Scope of variables
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 their scope is between its declaration point and the end of that
function.
Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But if we
want a variable to store a concrete value at the same moment that it is declared. We must initialize
the variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:
Syntax: Datatype VariableName = initial_value ;
Example: int a = 0
The other way to initialize variables, known as constructor initialization, is done by
enclosing the initial value between parentheses (()):
Syntax: Datatype VariableName (initial_value) ;
Example: int a(0);
Both ways of initializing variables are valid and equivalent in C++.
(d) Operators:

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of operators:

Page No: 10
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

i. Arithmetic Operators
ii. Relational Operators
iii. Logical Operators
iv. Bitwise Operators
v. Assignment Operators
vi. Other Operators

(i) Arithmetic Operators:


There are following arithmetic operators supported by C++ language:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
Modulus Operator and remainder of after an integer
% B % A will give 0
division
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

(ii) Relational Operators:


There are following relational operators supported by C++ language

Operator Description Example


Checks if the values of two operands are equal or (A == B) is not true.
==
not, if yes then condition becomes true.
Checks if the values of two operands are equal or (A != B) is true.
!= not, if values are not equal then condition
becomes true.
Checks if the value of left operand is greater than (A > B) is not true.
> the value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is less than the (A < B) is true.
< value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is greater than (A >= B) is not true.
>= or equal to the value of right operand, if yes then
condition becomes true.
Checks if the value of left operand is less than or (A <= B) is true.
<= equal to the value of right operand, if yes then
condition becomes true.

(iii) Logical Operators:


There are following logical operators supported by C++ language

Operator Description Example


Called Logical AND operator. If both the operands
&& (A && B) is false.
are non-zero, then condition becomes true.
Called Logical OR Operator. If any of the two
|| (A || B) is true.
operands is non-zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the !(A && B) is true.

Page No: 11
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

logical state of its operand. If a condition is true,


then Logical NOT operator will make false.

(iv) Bitwise Operators:

Bitwise operator works on bits and perform bit-by-bit operation. The Bitwise operators
supported by C++ language are listed in the following table.
Operator Description Example
Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
&
the result if it exists in both operands. 1100
Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011
|
exists in either operand. 1101
Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
^
it is set in one operand but not both. 0001
Binary Ones Complement Operator is (~A ) will give -61 which is 1100
~ unary and has the effect of 'flipping' 0011 in 2's complement form due to
bits. a signed binary number.
Binary Left Shift Operator. The left A << 2 will give 240 which is 1111
operands value is moved left by the 0000
<<
number of bits specified by the right
operand.
Binary Right Shift Operator. The left A >> 2 will give 15 which is 0000
operands value is moved right by the 1111
>>
number of bits specified by the right
operand.

The truth tables for &, |, and ^ are as follows:


p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows:

A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

(iv) Increment/ Decrement Operator:


Example
Operator Description
Assume A=10
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

(v) Assignment Operators:


There are following assignment operators supported by C++ language:

Page No: 12
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Operator Description Example


Simple assignment operator, Assigns values C = A + B will assign value of A
=
from right side operands to left side operand + B into C
Add AND assignment operator, It adds right C += A is equivalent to C = C +
+= operand to the left operand and assign the A
result to left operand
Subtract AND assignment operator, It C -= A is equivalent to C = C - A
-= subtracts right operand from the left operand
and assign the result to left operand
Multiply AND assignment operator, It C *= A is equivalent to C = C *
*= multiplies right operand with the left operand A
and assign the result to left operand
Divide AND assignment operator, It divides C /= A is equivalent to C = C /
/= left operand with the right operand and A
assign the result to left operand
Modulus AND assignment operator, It takes C %= A is equivalent to C = C
%= modulus using two operands and assign the % A
result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2
^=
operator
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

(vi) Other Operators


There are few other operators supported by C++ Language.
Operator Description
sizeof operator returns the size of a variable. For example, sizeof(a), where a
sizeof
is integer, will return 4.
?: Conditional operator. If Condition is true ? then it returns value X : otherwise
Condition ? value Y
X:Y
Comma operator causes a sequence of operations to be performed. The value
, of the entire comma expression is the value of the last expression of the
comma-separated list.
. (dot) and - Member operators are used to reference individual members of classes,
> (arrow) structures, and unions.
Casting operators convert one data type to another. For example, int(2.2000)
Cast
would return 2.
& Pointer operator & returns the address of an variable. For example &a; will

Page No: 13
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

give actual address of the variable.


Pointer operator * is pointer to a variable. For example *var; will pointer to a
*
variable var.

Operators Precedence in C++:


Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated
first.
Category Operator Associativity
Postfix ( ) [ ] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

=======================================================================

CONTROL STATEMENTS:

1. Decision Making Statements:


The decision making statements in C++ are:
• if statements
• if…else statements
• nested if…else statements
• switch statements
1.1. The if Statement:
An if statement consists of a condition followed by one or more statements.
Syntax:
if(condition)
{
//Statements will execute if the condition is true

Page No: 14
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

}
If the condition evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y;
cout<<”Enter two values: “;
cin>>x>>y;
if( x > y )
{
cout<<x <<“ is Greater";
}
}

Output:
Enter two values: 25 15
25 is Greater
1.2. The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the
Condition is false.
Syntax:
if(Condition)
{
//Executes when the Condition is true
}
else
{
//Executes when the Condition is false
}
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y;
cout<<”Enter two values: “;
cin>>x>>y;
if( x > y )
{
cout<<x <<“ is Greater";
}
else
{
cout<<y<<” is Greater ";
}
}

Page No: 15
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Output:
Enter two values: 25 50
50 is Greater
1.3. The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement. When using if , else if , else statements
there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
if(Condition 1)
{
//Executes when the Condition 1 is true
}
else if(Condition 2)
{
//Executes when the Condition 2 is true
}
else if(Condition 3)
{
//Executes when the Condition 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y, z;
cout<<”Enter three values: “;
cin>>x>>y>>z;
if( (x>y) &&(x>z) )
{
cout<<x<<” is Greater”;
}
else if( y>z )
{
cout<<y<<” is Greater";
}
else
{
cout<<z<<” is Greater";
}
}

Page No: 16
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Output:
Enter three values: 20 50 30
50 is Greater
1.4. Nested if...else Statement:
It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
if(Condition 1)
{
//Executes when the Condition 1 is true
if(Condition 2)
{
//Executes when the Condition 2 is true
}
}

Example:
using namespace std;
#include<iostream>
main( )
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
cout<<"X = 30 and Y = 10");
}
}
}
Output:
X = 30 and Y = 10
1.5. The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression)
{
case value1 :
//Statements
break;
case value2 :
//Statements
break;
.
.
.
//Can have any number of case statements.
default :

Page No: 17
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

//Statements
break; //Optional
}
Rules apply to a switch statement:
• The variable used in a switch statement can only be a byte, short, int, or char.
• We can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
• The value for a case must be the same data type as the variable in the switch and it must be
a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
using namespace std;
#include<iostream>
main()
{
char input;
cout<<”Enter a Character: “;
cin>>input;
switch(input)
{
case 'A' :
cout<<"A is an Vowel";
break;
case 'E' :
cout<<"E is an Vowel ";
break;
case 'I' :
cout<<”I is an Vowel ";
break;
case 'O' :
cout<<”O is an Vowel ";
Break;
case 'U' :
cout<<"U is an Vowel ";
break;
default :
cout<<"Input Value is not an Vowel";
}
}
}
Output:
Enter a Character: U

Page No: 18
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

U is an Vowel
2. Loops:
When we need to execute a block of code several number of times referred to as a loop. C++
has three looping mechanisms. They are as follows:
• while Loop
• do...while Loop
• for Loop
2.1. The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of
times till the condition becomes false.
Syntax:
while(Condition)
{
//Statements
}
During execution, if the Condition result is true, then the statements inside the loop will be
executed. This will continue as long as the condition is true. The key point of the while loop is that
the loop will not get executed if the condition is false, the loop body will be skipped and the first
statement after the while loop will be executed.
Example:
using namespace std;
#include<iostream>
main( )
{
int x = 10;
while( x < 15 )
{
cout<<"value of x : "<< x ;
x++;
}
}

Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
2.2. The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop will execute at least
one time whether the condition is true or false.
Syntax:
do
{
//Statements
}while(Condition);

Page No: 19
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

In do…while loop the Condition appears at the end of the loop, so the statements in the loop
execute once before the Condition is tested. If the Condition is true, the flow of control jumps back
up to do, and the statements in the loop execute again. This process repeats until the Condition is
false.
Example:
using namespace std;
#include<iostream>
main( )
{
int x = 10;
do
{
cout<<”value of x : " <<x;
x++;
}while( x < 15 );
}

Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
2.3. The for Loop:
A for loop is a repetition control structure that allows to write a loop efficiently that needs
to execute a specific number of times. A for loop is useful when we know how many times a task is
to be repeated.
Syntax:
for (initial condition; Ending Condition; increment/decrement)
{
//Statements
}
The flow of control in for loop:
• The initialization step is executed first, and only once. This step allows us to declare and
initialize any loop control variables.
• Next, the Condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement of for
loop.
• After the body of the for loop executes, the flow of control jumps back up to the
increment/decrement statement. This statement allows us to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
Condition.
• The Condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment/decrement step, then Condition). After the Condition is
false, the for loop terminates.
Example:
using namespace std;
#include<iostream>

Page No: 20
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

main( )
{
for(int x = 10; x <=15; x++)
{
cout<<"value of x : "<<x;
}
}

Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
3. The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside
any loop or a switch statement. The break keyword will stop the execution of the innermost loop
and start executing the next line of code after the block.
Syntax:
The syntax of a break statement is: break;
Example:
using namespace std;
#include<iostream>
main( )
{
for(int x = 0; x <5; x++)
{
if(x==3)
break;
cout<<"value of x : "<<x;
}
}

Output:
value of x : 0
value of x : 1
value of x : 2
4. The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
• In a while loop or do/while loop, flow of control immediately jumps to the Condition.
Syntax:
The syntax of a continue is: continue;
Example:
using namespace std;

Page No: 21
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

#include<iostream>
main( )
{
for(int x = 0; x <5; x++)
{
if(x==3)
continue;
cout<<"value of x : "<<x;
}
}
Output:
value of x : 0
value of x : 1
value of x : 2
value of x : 4
value of x : 5
=======================================================================
ARRAYS

An array is a data structure which allows a collective name to be given to a group of


elements which all have the same type. An individual element of an array is identified by its own
unique index (or subscript). The index must be an integer and indicates the position of the
element in the array. Thus the elements of an array are ordered by the index.

Arrays can be of two types: one dimensional and multi-dimensional arrays.

(i) One Dimensional Array:

Declaring an Array:
Syntax of declaring an array is:
DataType ArrayName[dimension/order];

Examples:
int Age[12]; //declares an array of 12 values, each one being an integer.
float Grade[100]; //declares an array of 100 floating-point values.

Initializing an Array:
Syntax used for initializing array is:
DataType ArrayName[dimension] = { element1, element2, …, elementn};

Examples:
int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};

Processing the Elements of an Array:


After initializing an array, its elements are counted from left to right. Each element of the
array, also called a member of the array, has a specific and constant position. The position of an
item is also called its index. The first member of the array, the most left, has an index of 0. The
second member of the array has an index of 1. Since each array has a number of items which can be
specified as n, the last member of the array has an index of n-1.

Page No: 22
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Example: 1 To access specific members of an array

#include <iostream>
using namespace std;
main( )
{
int arr[ ] = {44, 720, 96, 468, 6};
cout << "2nd member = " << arr[1] << endl;
cout << "5th member = " << arr[4] << endl;
}

Output:
2nd member = 720
5th member = 6

Example: 2 To access all members of an array

#include <iostream>
using namespace std;
main( )
{
int arr[ ] = {44, 720, 96, 468, 6};
for(int i=0;i<5;i++)
{
cout << "The array values are: " << arr[i] << “\t”;
}
}

Output:
The array values are: 44 720 96 468 6

Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, a list of one-dimensional arrays. It is mainly used to perform operations on
Matrix.
Syntax of declaring an array is:
DataType ArrayName[dimension1] [dimension2];

Example:
int a[3] [4]; //declares an 3x4 2D Matrix named as “a” to store integer values..

A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can be
shown as below:

Page No: 23
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where
a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays:


Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The following initialization is equivalent to previous example:

int Arr[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:
int Arr = Arr[2][3];

Example:1
using namespace std;
#include<iostream>
main( )
{
int a[3][3],b[3][3],c[3][3];
int i,j;
cout<<"Enter the values for Matrix 1: ";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
}
cout<<"Enter the values for Matrix 2: ";
for(i=0;i<3;i++)

Page No: 24
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

{
for(j=0;j<3;j++)
{
cin>>b[i][j];
}
}
cout<<"The Resultant Matrix is....\n ";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j];
}
cout<<"\n";
}
}

Output:
Enter the values for Matrix 1:
2 2 2
2 2 2
2 2 2
Enter the values for Matrix 2:
6 6 6
6 6 6
6 6 6
Resultant Matrix is....
8 8 8
8 8 8
8 8 8
Example: 2
Passing Array as argument
using namespace std;
#include <iostream>
void printarray (int arg[ ], int length)
{
for (int n=0; n<length; ++n)
cout << arg[n] <<"\t";
cout <<"\n";
}
main( )
{
int arr1[ ] = {5, 10, 15};
int arr2[ ] = {2, 4, 6, 8, 10};
printarray (arr1,3);
printarray (arr2,5);
}

Output:
5 10 15
2 4 6 8 10

=======================================================================

Page No: 25
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

STRUCTURE OF C++ PROGRAM:


A typical C++ program would contain four sections. These sections may be placed in
separate code files and then compiled independently or jointly.

It is a common practice to organize a program into three separate files. The class
declarations are placed in a header file and the definitions of member functions go into another
file.
A SIMPLE C++ PROGRAM

using namespace std;


#include <iostream>
int main( )
{
cout<<”C++ is better than C.\n”;
return 0;
}
Benefits of OOPS:
1. Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
2. 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.
3. The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
4. It is easy to partition the work in a project based on objects.
5. Object-oriented systems can be easily upgraded from small to large systems.
6. Software complexity can be easily managed.

FUNCTIONS:
A function is defined as a set of program statements that can be processed independently.

The process of splitting a large program into smaller tasks and designing them separately is
called modular programming or divide and conquer technology.
Advantages of Function:
• Modular Programming.
• Reduction in the amount of work and development time.

Page No: 26
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

• Reduction in the size of the program due to code reusability.


• Functions can be accessed repeatedly without development.
Components of a Function:
1. Function Declaration / Prototyping.
2. Function Definition.
3. Function Call.
1) Function Declaration / Prototyping:
• Function prototyping is one of the major improvements added to C++ functions.
• The prototype describes the function interface to the compiler by giving details such as the
number and type of arguments and the type of return values.
• Function prototype is a declaration statement in the calling program and is of the form

Syntax:

return type function-name (argument-list);


The argument list contains the types and names of arguments that must be passed to the
function.
Example: float volume(int x, float y);
2) Function Definition:
• The exact function is called the function definition.
• The first line of the function definition is known as “function declaration” which is followed
by function body.
Syntax:
return type function-name (argument-list)
{
//statements;
}
Example:
void add (int a , int b)
{
c = a+b;
cout << “sum = “ << c;
}
3) Function Call:
• This will be present in the main( ) function.
• It calls the function that is already defined with the necessary arguments.
Syntax:
function-name (arguments);
Example: Add (10, 20);
Actual Parameter: The arguments specified in the function call are known as Actual Parameter.
Formal Parameter: The arguments given in the function declaration is known as Formal
Argument.

Page No: 27
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Calling Function (Or) Caller: A function that calls a defined function with arguments is called
Calling function.
Called Function (Or) Callee: The function that is called by another function is called a Callee.
PARAMETER PASSING:
❖ It is a method for communication between the calling function and the called function.
❖ There are three types of parameter passing techniques, they are
1. Call by Value (or) Pass by Value
2. Call by Address (or) Pass by Address
3. Call by Reference (or) Pass by Reference
Rules For Parameter Passing:
1. Number of arguments in function call and function declarator must be same.
2. Data type of arguments in function call and function declarator must be same.
1. Call By Value:
❖ It is the default mechanism of parameter passing.
❖ This process will not change the contents of arguments in the calling function [actual
arguments].
❖ In this process only a copy of the actual argument is passed to the formal argument.
❖ Even if the value is changed in the called function, the value will not be changed in the
calling function.
Example:
using namespace std;
#include<iostream>
void swap (int x, int y); //Function Declaration
main ( )
{
int a = 10, b = 20;
cout <<”Values Before Swapping: “<<a << b;
swap (a,b); //Function call
cout <<”Values After Swapping: “<<a << b;
}
void swap (int x, int y) //Function Definition
{
int t;
t = x;
x = y;
y = t;
}
2) Call By Address:
❖ In this process instead of passing the value of actual arguments the address of actual
arguments will be passed.
❖ The value of actual parameter will be referenced from memory.
❖ In this process the actual value will be changed.
Example:
using namespace std;
#include<iostream>

Page No: 28
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

void swap ( int *x, int *y); //Function Declaration


void main ( )
{
int a,b;
a = 10;
b = 20;
cout <<”Values Before Swapping: “<<a << b;
swap (&a, &b); //Function call
cout <<”Values After Swapping: “<<a << b;
}
void swap ( int *x, int *y) //Function Definition
{
int t;
t = *x;
*x = *y;
*y = t;
}
3) Call By Reference:
• This process has the functionality of call-by value.
• The main difference is that any modification in the formal parameter will be reflected in the
actual parameter.
• The function call is same as the call by value.
• In the function declarator, the parameter which are received by the reference must be
preceded by the & operator.
Example:
using namespace std;
#include<iostream>
void swap ( int &x, int &y); //Function Declaration
void main ( )
{
int a,b;
a = 10;
b = 20;
cout <<”Values Before Swapping: “<<a << b;
swap (a, b); //Function call
cout <<”Values After Swapping: “<<a << b;
}
void swap ( int &x, int &y) //Function Definition
{
int t;
t = x;
x = y;
y = t;
}
=======================================================================
FUNCTIONS WITH DEFAULT ARGUMENTS:
If the calling function does not provide any argument to the called function, the compiler
will execute the called function using Default arguments. Such functions are called as Default
argument Function.
Rule for Default argument Functions:

Page No: 29
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

• The default value must be given in the function declaration.


• Default arguments are useful in situations where some arguments always have the same
value.
• Default values must be added only from right to left.
Syntax: ReturnType FunctioName(arg1=value1, arg2=value2,……..argn=valuen);
Example: int Area(int radius, int PI=3.14);
value = Area (5); // one argument missing passes the value of 5 to radius and the function
use default value of 3.14 for PI.
Example Program:
using namespace std;
#include<iostream>
void product(int x=2, int y=5, int z=3, int c=4) ; //Default argument Function Declaration
main( )
{
product(6,2); //Function call with 2 default arguments will be passed
product(10,4,3); // Function call with 1 default arguments will be passed
product(4,6,5,2); // Function call with No default arguments will be passed
product( ); // Function call with 4 default arguments will be passed
}
void product(int x, int y, int z, int c) //Default argument Function Definition
{
mul=x*y*z*c;
cout<<"\nThe Product is="<<mul;
}

Output:
The Product is= 12
The Product is= 480
The Product is= 240
The Product is= 120
=========================================================================
inline Functions:
In case of very small functions inorder to avoid context switching, the entire function will
be loaded next to the function call. This function will be loaded in the main function itself.
This is called as inline function.
Syntax:
inline ReturnType FunctionName(arguments);
Example:
using namespace std;
#include<iostream>
inline void sum(int x, int y, int z); //inline function declaration
main( )
{
sum(12,5,15);
}
void sum(int x, int y, int z) //inline function definition
{
cout<<"\nThe Sum of three number is="<<(x+y+z);
}

Page No: 30
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Output:
The Sum of three number is= 32
POINTERS:
A pointer is a variable used to store the address of another variable. Like any variable or
constant, pointer must be declared before work with it. The general form of a pointer variable
declaration is:
DataType *variableName;
Where,
• DataType is the pointer's base type; it must be a valid C++ type
• variableName is the name of the pointer variable.
• The asterisk is being used to indicate a variable as a pointer
Following are the valid pointer declaration:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Using Pointers in C++:
Operations done with the pointers very frequently:
• First define a pointer variables
• Assign the address of a variable to a pointer
• Finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand.
Example:
#include <iostream>
using namespace std;
main( )
{
int x = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &x; // store address of var in pointer variable
cout << "Value of variable x : "<<x;
cout << "Address stored in ip variable: ";
cout << ip; // print the address stored in ip pointer variable
cout << "Value of *ip variable: ";
cout << *ip; // access the value at the address available in pointer
}

Output:
Value of variable x : 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

C++ Pointer to Pointer (Multiple Indirection)


A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that contains the actual
value as shown below.

Page No: 31
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int: int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:
#include <iostream>
using namespace std;
main ( )
{
int var; int *ptr; int **pptr;
var = 3000;
ptr = &var; // take the address of var
pptr = &ptr; // take the address of ptr using address of operator &
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
}

Output:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000

=======================================================================

CLASSES:

• Class is a unit which contains both data and the functions that operate on the data.
• The internal data of the class is called as data member and the functions are called
member function.
• The variables of a class are called objects or instances of a class.
• A class is a way to bind the data and its associated functions together.

Class Declaration:

Syntax:
class ClassName
{
AccessSpecifier:
//Data members
//Member Functions
};
Where,
• class is a keyword.

Page No: 32
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

• In place of Access Specifier public, private or protected can be used.


• The class declaration should end with a semicolon.

Access Control Specifiers:


(i) Private:
• It has strict access control.
• It is the default access specifier.
• Only the member function of the same class can access these members.
• They are inaccessible outside the class.
(ii) Public:
• It can be accessed by any function without any restriction from anywhere in the
program.
(iii) Protected:
• It is similar to that of private members and has more significance in Inheritance.

The variables declared inside the class are known as data members and functions are
known as member functions. Only the member functions can have access to the private data
members and member functions. However, the public members (both functions and data) can be
accessed from outside the class.

Defining Member Functions of a Class:


Member Functions of a Class can be defined in two ways:
1. Defining member Function Within a class
2. Defining member Function Outside a class

Defining member Function Within the class:


Example:
using namespace std;
#include<iostream>
class Example
{
public:
int x,r1,r2;
void get( )
{
cout<<”Enter a value: “;
cin>>x;
}
void Square( )
{
r1=x*x;
cout<<”Square of a number= “<<r1;
}
void Cube( )
{
r2=x*x*x;
cout<<”Cube of a number= “<<r2;

Page No: 33
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

}
};
void main( )
{
Example e1;
e1.get( );
e1.Square( );
e1.Cube( );
}

Defining member Function Outside the class:


To define a member function outside the class it must follow the following syntax,
Syntax:
ReturnType className :: FunctionName(arguments)
{
//definition part of the function
}
Where,
• ReturnType –value returned from the function
• className – function present in which function
• :: - Scope Resolution operator used to access the function outside the class
• FunctionName – name of the function
Example:
using namespace std;
#include<iostream>
class Example
{
public:
int x,r1,r2;
void get( ); //Function Declaration
void Square( );
void Cube( );
};
void Example :: get( ) // Function Definition
{
cout<<”Enter a value: “;
cin>>x;
}
void Example :: Square( )
{
r1=x*x;
cout<<”Square of a number= “<<r1;
}
void Example :: Cube( )
{
r2=x*x*x;
cout<<”Cube of a number= “<<r2;
}

void main( )

Page No: 34
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

{
Example e1;
e1.get( ); e1.Square( ); e1.Cube( );
}

=======================================================================

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. When a program is executed,
the objects interact by sending messages to one another.

Syntax for object creation:

className objectName;

Example:
• Student S1; //object named S1 was created.
• More than one object can be created using a single statement: Student S1,S2,….Sn;
Pointer Objects:
• In C++ pointers can also have an address for an object. They are known as pointers to
objects.
• A pointer to an object contains an address of that object.
• Object pointers are useful in creating objects at run time.
• Syntax for creating Pointer Object:
ClassName *ptrObj;
• Using pointer objects member of a class can be accessed with the help of the following
syntax:
PtrObj →MemberFunction( );
Program:
using namespace std;
#include<iostream>
class student
{
public: int a, b, c, sum;
void getdetails( )
{
cin >> a >> b >> c;
}
void calculate( )
{
sum = a+b+c;
}
void printdetails( )
{
cout << sum;

Page No: 35
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

}
};
main( )
{
student *s1;
s1 -> a=10;
s1 -> b=15;
s1 -> c=25;
s1 -> calculate( );
s1 -> printdetails( );
}
CONSTANT OBJECTS:
• Constant objects are not modifiable.
• It is denoted by using the keyword “const”.
• Const object is not allowed to do operations which modify the object.
• Only the functions that are defined as const can be accessed by const objects. Even public
variables of the object are not modifiable.
• When we do not want any accidental change in the objects properties, we should define the
object as const object.
Example: const matrix X(m,n); //Object X is constant
X is a constant object of the class matrix, any attempt to modify the values of m and n will
generate compile-time error. A constant object can call only const member functions.
Program:
using namespace std;
#include<iostream>
class student
{
public:
int rno;
char name[10], char addr[10];
void printdetails ( ) const //const function
{
cout << “Roll No: “<<rno;
cout << “Name: “<<name;
cout << “Address: “<<addr;
}
};
void main( )
{
student s;
s1.rno = 1; s1.name = “anju”; s1.addr = “nagercoil”;
s1.printdetails( );
const student s2=s1; //constant object
s2.printdetails( );
s2.rno = 5; //Error: using constant object trying to
// modify a value of a member
cout << s4.rno;
}

=======================================================================

Page No: 36
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Static Members:
• A data member of a class can be qualified as static.
• Properties of static member variables are,
• They are normally used to maintain values commonly to the entire class.
• It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
• Only one copy of that member is created for the entire class and is shared by all the objects
of that class.
• It is visible only within the class, but its life time is the entire program.
• They cannot be declared either const or volatile.
Syntax:
static datatype datamember; and static datatype memberfunction( );
Example:
static int s;
static int add(s);
Example Program:
using namespace std;
#include<iostream>
class Flowers
{
public:
char n[10];
static int c;
void get( )
{
cout<<"\nEnter the Flower name: ";
cin>>n;
c++;
}
static void put( )
{
cout<<"\nThe total number of flowers are : "<<c;
}
};
int Flowers::c;
main( )
{
Flowers a1,a2,a3,a4;
a1.get( );
a2.get( );
a3.get( );
a4.get( );
a1.put( );
}
Output:
Enter the flower name: Rose
Enter the flower name: Lotus
Enter the flower name: Lilly
Enter the flower name: Jasmine
The total numbers of flowers are: 4

=======================================================================

Page No: 37
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

NESTED CLASS:
➢ A class declared as a member of another class is called as a nested class or a class within
another class.
➢ The name of the nested class is local to the enclosing class.
➢ Defining the nested class as “private” only nesting class can refer to it others cannot.
➢ Defining the nested class in the “public” part of the nesting class, it is available to those who
have access to the nesting class.
Syntax:
class outer class name
{
private:
// data of outer class
public:
class inner class name
{
private:
// data of inner class
public:
// data of inner class
};
};
===============================================
========================
LOCAL CLASS:
Classes can be defined and used inside a function or a block. Such classes are called local
classes.
• It cannot access the private variables of the class. One way to access private variables of the
class is to become a friend of it.
• Local classes can use global variables (declared above the function) and static variables
declared inside the function but cannot use automatic local variables. The global variables
should be used with the scope operator (::).
• There are some restrictions in constructing local classes. They cannot have static data
members and member functions must be defined inside the local classes.
• Enclosing function cannot access the private members of a local class. However, we can
achieve this by declaring the enclosing function as a friend.
Syntax:
ReturnType FunctionName(args)
{
class className
{

};
className obj;
}
Syntax Example:
void Display( )
{
class Local
{

};

Page No: 38
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

Local obj;
}
Program:
void display( )
{
class local
{
public:
int x, y, z;
void get( )
{
cout<<”Enter the values:”;
cin>>x>>y>>z;
}
void add( )
{
z=x+y;
cout<<”Sum of two numbers = ”<<z;
}
}; //end of local class
local obj;
obj.get( );
obj.add( );
} //end of function
void main( )
{
void display( );
display( ); //Function call
}
=======================================================================

QUESTIONS:
1) What are the Features of OOP’s & how are they implemented in C++? (or) Explain object-
oriented paradigm with all its essential elements. (or) Explain the following concepts of
object oriented programming in detail with an example.
(i) Data abstraction (ii) Inheritance
(iii) Polymorphism (iv) Objects.
2) Describe the advantages and applications of OOPs technology.
3) State the merits and demerits of object oriented methodology.
4) Mention about the Native/ Basic data types in C++.
5) List out the C++ operators and explain those operators with example.
6) Explain about different control statements in C++.
7) Define Array. Explain its types with an example for each type.
8) What are the different ways of argument passing and explain it with suitable example
programs?
9) Explain about Default argument function with an example to multiply six numbers in detail.
10) What is an inline function? With an example.

Page No: 39
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G

11) What are the differences between pointers to constants and constant pointers?
12) Explain about class and object in detail with an example by defining the members inside and
outside the class.
13) Briefly explain the concept of static members with simple example programs.

14) Explain about Nested class with an example of nesting three classes.
15) Explain about Local class with an example.
16) Write a C++ program to extract the elements placed on the odd position of the array.
17) Write a C++ program to print the sum of all squares between 1 and N, where N is a number
accepted from the keyboard(i.e.) 1+4+…..+(N*N).

Page No: 40

You might also like