COMPUTER PROGRAMMING I NOTES
COMPUTER PROGRAMMING I NOTES
(C ++ PROGRAMMING)
0
PROGRAMMING PARADIGMS
Programming paradigms refer to the different programming approaches that can be used to
write computer programs. Comparison will be made between procedure oriented, structure
oriented, event driven and object oriented paradigms.
POP follows a step-by-step approach to break down a task into a collection of variables and
routines (or subroutines) through a sequence of instructions. Each step is carried out in a
systematic manner so that a computer can understand what to do. The program is divided into
small parts called functions and then it follows a series of computational steps to be carried
out in order.
It follows a top-down approach to actually solve a problem, hence the name. Procedures
correspond to functions and each function has its own purpose. Dividing the program into
functions is the key to procedural programming. So a number of different functions are written
in order to accomplish the tasks. POP focuses on procedural abstractions. Commonly used
POP languages are Pascal and FORTRAN.
OOP and POP are such high-level programming paradigms that use different approaches to
create a program to solve a particular problem in the less time possible. While an object-
oriented program depends mainly upon data rather than the algorithm, a procedure-oriented
program follows a step-by-step approach to solve a problem. OOP, of course, has a little edge
over POP in areas such as data security, ease of use, accessibility, operator overloading, and
more.
OOP POP
OOP takes a bottom-up approach in POP follows a top-down approach.
designing a program.
Program is divided into objects depending Program is divided into small chunks based
on the problem. on the functions.
Each object controls its own data. Each function contains different data.
1
Focuses on security of the data irrespective Follows a systematic approach to solve the
of the algorithm. problem.
The main priority is data rather than Functions are more important than data in a
functions in a program. program.
The functions of the objects are linked via Different parts of a program are
message passing. interconnected via parameter passing.
Data hiding is possible in OOP No easy way for data hiding.
Inheritance is allowed in OOP. No such concept of inheritance in POP.
Operator overloading is allowed. Operator overloading is not allowed.
C++, java. Pascal, Fortran.
Structured Programming
Event-Driven Programming
2
Object Oriented Programming
Many of the most widely used programming languages (such as C++, Java, Python, etc.)
are multi-paradigm and they support object-oriented programming to a greater or lesser degree.
Object-oriented programming shifts the focus of attention to the objects, that is, to the aspects
on which the problem is centered. A program designed to maintain bank accounts would work
with data such as balances, credit limits, transfers, interest calculations, and so on. An object
representing an account in a program will have properties and capacities that are important for
account management. OOP objects combine data (properties) and functions (capacities). A
class defines a certain object type by defining both the properties and the capacities of the
objects of that type. Objects communicate by sending each other “messages,” which in turn
activate another object’s capacities.
■ easy re-use: objects maintain themselves and can therefore be used as building blocks for
other programs
■ low maintenance requirement: an object type can modify its own internal data representation
without requiring changes to the application.
3
Fundamentals of Object Oriented Programming
OOP treats data as a critical element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the functions that operate on it and protects
it from accidental modification from outside functions. OOP allows us to decompose a
problem into a number of entities called objects and then builds data and functions around
these entities. The combination of data and methods make up an object.
Features
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data is hidden and cannot be accessed by external functions.
4. Objects may communicate with each other though functions.
5. New data and functions can be easily added whenever necessary.
6. Follows bottom-up approach in program design.
1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message communication
4
1. Objects
Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program must handle.
Programming problem is analyzed in terms of objects. 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 message to the account object
requesting for the bank balance. Each object contains data and code to manipulate the data.
---------------------------------------------------
Object: STUDENT
---------------------------------------------------
DATA
Name
Date-of-birth
Marks
------------------------------------------------------------
FUNCTIONS
Total
Average
Display
Objects serve two purposes: They promote understanding of the real world and provide a
practical basis for computer implementation. All Objects have identity and
are distinguishable.
2. Classes
An Object class describes a group of objects with similar properties (attributes), common
behavior (operations) and common relationships to other objects. Objects in a class have the
same attributes and behavior patterns. The entire set of data and code of an object can be made
a user defined data type with the help of a class.
E.g. Mango, Apple, Orange are the members of the class fruit. If fruit has been defined as a
class then the statement fruit mango; will create an object mango belonging to the class fruit.
A class serves as a blue print or a plan or a template. It specifies what data and what
functions will be included in objects of that class. Class with attributes, objects with values.
5
An attribute is a data value held by the objects in a class.
3. Data Abstraction
It consists of focusing on the essential inherent aspects of an entity. Most modern languages
provide data abstraction, but the ability to use inheritance and polymorphism provides
additional power. Classes use the concept of abstraction, they are known as Abstract Data
Types.
4. Encapsulation
It is also termed as information hiding. The wrapping up of data and functions into single unit
is known as encapsulation. It is the most essential feature of a class. The data is not accessible
to the outside and only those functions in the class can access it.
5. Inheritance
The bird ROBIN is a part of the class FLYING BIRD that is again a part of the class BIRD. In
Object Oriented Programming, the concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing class without modifying it.
6
6. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior is different
instances. The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.
7. Dynamic binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at run time. It is associated with polymorphism and inheritance. A
function call associated with a polymorphic reference depends on the dynamic type of that
reference.
8. Message communication
An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic steps:
7
C ++ Fundamentals
When learning to program in any programming language, it’s best just to learn the “rules of
the game.”
Modern programs are projects composed of many of individual program modules that have to
be linked together in order to be run. In fact most developer systems have their own integrated
development environment (IDE) and programs are developed in phases within the IDE.
8
Special Characters Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ?
_ # <= >= @
Formatting characters backspace, horizontal tab, vertical tab, form feed, and carriage
return
Punctuators
Braces { } Opening and closing braces indicate the start and end of a
compound statement.
Operators
Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator etc.
9
1. Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric)
operation. You can use the operators +, -, *, and / with both integral and floating-point data
types.
2. Relational operators
The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational expression
returns zero when the relation is false and a non-zero when it is true. The following table
shows the relational operators.
3. Logical operators
The logical operators are used to combine one or more relational expression. The logical
operators are:
Operators Meaning
|| OR
&& AND
! NOT
10
4. Unary operators
C++ provides two unary operators for which only one variable is required. For Example a = -
50; a = + 50; Here, plus sign (+) and minus sign (-) are unary because they are not used
between two variables.
5. Assignment operator
The assignment operator '=' is used for assigning a value to a variable. This operator takes
the expression on its right-hand-side and places it into the variable on its left-hand-side.
For example: m = 5;
The operator takes the expression on the right, 5, and stores it in the variable on the left, m.
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
This program would first assign the value of a to i, and then assign value of b to variable i.
So, at the end, variable i would contain the value 2.
Keywords
There are some reserved words in C++ which have predefined meaning to compiler called
keywords. These words may not be used as identifiers. Some commonly used Keywords are
given below:
11
Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a sequence of
characters taken from C++ character set. In previous program x, y and z are identifiers of
variables. The rule for the formation of an identifier are:
An identifier can consist of alphabets, digits and/or underscores. It must not start with a digit
C++ is case sensitive that is upper case and lower case letters are considered different from
each other. It should not be a reserved word.
Constants
Constants (often referred to as literals) are data items that never change their value during the
execution of the program. The following types of literals are available in C++.
1. Integer Constants
12
Integer constants are whole number without any fractional part. C++ allows three types of
integer constants. Decimal integer constants: It consists of sequence of digits and should not
begin with 0 (zero). For example 124, - 179, +108. Octal integer constants: It consists of
sequence of digits starting with 0 (zero). For example. 014, 012. Hexadecimal integer
constant: It consists of sequence of digits preceded by ox or OX.
2. Character constants
A character constant in C++ must contain one or more characters and must be enclosed in
single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which
cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These
characters can be represented by using an escape sequence. An escape sequence represents a
single character.
3. Floating constants
They are also called real constants. They are numbers having fractional parts. They may be
written in fractional form or exponent form. A real constant in fractional form consists of
signed or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -
0.627 etc.
4. String Literals
A sequence of character enclosed within double quotes is called a string literal. String literal
is by default (automatically) added with a special character ‘\0' which denotes the end of the
string. Therefore the size of the string is increased by one character. For example
"COMPUTER" will be represented as "COMPUTER\0" in the memory and its size is 9
characters.
C++ supports a large number of data types. The built in or basic data types supported by C++
are integer, floating point and character. C++ also provides the data type bool for variables that
can hold only the values True and False.
13
Some commonly used data types are summarized in table along with description.
Type Description
int Small integer number
long int Large integer number
float Small real number
double Double precision real number
long double Long double precision real number
char A Single Character
A C++ program is made up of objects with their accompanying member functions and global
functions, which do not belong to any single particular class. Each function fulfills its own
particular task and can also call other functions
14
Line 4 The “using” directive allows direct access to the names of the std namespace. Predefined
names in C++ are to be found in the std (standard) namespace.
Line 5 All C++ programs must have a main. “main” is a function of type “int”. The body of
“main” is contained within {}.
Line 6 begins with “cout” which is a predefined instance of the stream “ostream”. The name
cout (console output) designates an object responsible for output. The two less-than symbols,
<< is an insertion operator, that inserts what follows into the stream “cout. endl (end of line)
causes a line feed
Line 7 The statement “return 0”; terminates the function main() and also the program, returning
a value of 0 as an exit code to the calling program. It is standard practice to use the exit code
0 to indicate that a program has terminated correctly.
Line 8 } (curly bracket) marks the end of the code.
Note that every statement must end with a semi-colon (;).
Variables
A variable is a temporary storage that is created to hold certain amount of data in a program.
A variable must be declared before it is defined and a variable must be defined before you can
use it in a program. This declaration may appear anywhere in the program, as long as it appears
before the variable is first used. The declaration creates the object.
When you define a variable the type is specified and an appropriate amount of memory
reserved. This memory space is addressed by reference to the name of the variable. A simple
definition has the following syntax:
SYNTAX: type name1 [name2 ... ];
This defines the names of the variables in the list name1 [, name2 ...] as variables of the type
type. E.g : char c; int i, ;double x, y, size;float a; etc.
For the following declaration:
int n;
The name of the object is n, the type (or class) is int. The object does not yet have a value.
n = 66; //now it has a value
15
or
int n=66; //This declaration also gives a value to n
16
Output: The sum is 35
Program 2:
//mean2.cpp
// this program calculates the mean of three numbers.
// and helps learns about variables.
#include <iostream>
using namespace std;
int main()
{
float mean;
cout << "My Second C++ Program.\n\n";
mean = (12+5+10)/3;
cout << mean;
return 0;
} //end main
Output: 9
STATEMENTS
Statements are the instructions given to the computer to perform any kind of action. Action
may be in the form of data movement, decision making etc. Statements form the smallest
executable unit within a C++ program. Statements are always terminated by semicolon.
Compound Statement
A compound statement is a grouping of statements in which each individual statement ends
with a semi-colon. The group of statements is called block. Compound statements are enclosed
17
between the pair of braces ({}.). The opening brace ({) signifies the beginning and closing
brace (}) signifies the end of the block.
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This
is quite useful when the syntax of the language needs to specify a statement but the logic of
the program does not need any statement. This statement is generally used in for and while
looping statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++
provides the following statements for implementing the selection control structure.
if statement
if else statement
nested if statement
If statement
Syntax of the if statement
if (condition) {
statement(s);
}
If else statement
syntax of the if - else statement
if (condition) {
statement1;
else
statement2;
}
18
From the above flowchart; for the if statement: it is clear that the given condition is evaluated
first, then if the condition is true, statement is executed; otherwise it is skipped.
For the if-else statement, if the condition is true, statement1 is executed. If the condition is
false, statement2 is executed. It should be kept in mind that statement1 and statement2 can be
single or compound statements.
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement :
if (condition 1)
{
If (condition 2)
{
statement(s);
}
}
if (condition 1)
statement 1;
else
if (condition 2)
statement2;
19
else
statement3;
if-else-if example
if (percentage>=60)
cout<<"1st division";
else
if (percentage>=50)
cout<<"2nd division";
else
if(percentage>=40)
cout<<"3rd division";
else
cout<<"Fail" ;
LOOPING
Looping is also called a repetitive control structure. Sometimes we require a set of statements
to be executed a number of times by changing the value of one or more variables each time to
obtain a different result. This type of program execution is called looping. C++ provides the
following construct:
while loop
do-while loop
for loop
While loop
Syntax of while loop:
while (condition)
{
statement(s);
}
20
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly
as long as the condition remains true. As soon as the condition becomes false, it comes out of
the loop and goes to the statement next to the ‘while’ loop.
do-while loop
Syntax of do-while loop:
do
{ statements;
}
while (condition);
21
Note: That the loop body is always executed at least once. One important difference between
the while loop and the do-while loop is the relative ordering of the conditional test and loop
body execution. In the while loop, the loop repetition test is performed before each execution
of the loop body; the loop body is not executed at all if the initial test fail. In the do-while loop,
the loop termination test is performed after each execution of the loop body. Hence, the loop
body is always executed least once.
for loop
It is a count controlled loop in the sense that the program knows in advance how many times
the loop is to be executed.
syntax of for loop:
for (initialization; decision; increment/decrement)
{
statement(s);
}
The flow diagram indicates that in for loop three operations take place:
1. Initialization of loop control variable
2. Testing of loop control variable
3. Update the loop control variable either by incrementing or decrementing.
22
Operation (1) is used to initialize the value. On the other hand, operation (2) is used to test
whether the condition is true or false. If the condition is true, the program executes the body
of the loop and then the value of loop control variable is updated. Again it checks the condition
and so on. If the condition is false, it gets out of the loop.
Jump Statements
The jump statements unconditionally transfer program control within a function.
goto statement
break statement
continue statement
23
ARRAYS
An array is a collection of data elements of same data type. It is described by a single name
and each element of an array is referenced by using array name and its subscript number.
Declaration of Array
Type arrayName[numberOfElements];
For example:
int Age[5] ;
float cost[30];
Examples:
cout << age[4]; //print an array element
age[4] = 55; // assign value to an array element
cin >> age[4]; //input element 4
25
TWO DIMENSIONAL ARRAY
It is a collection of data elements of same data type arranged in rows and columns (that is, in
two dimensions).
Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
A two-dimensional array can be initialized along with declaration. For two dimensional array
initialization, elements of each row are enclosed within curly braces and separated by commas.
All rows are enclosed within curly braces.
To access the elements of a two-dimensional array, we need a pair of indices: one for the row
position and one for the column position.
The format is:
name[rowIndex][columnIndex].
Examples:
cout << A[1][2]; //print an array element
A[1][2] = 13; // assign value to an array element
cin >> A[1][2]; //input element
26
Using Loop to input a Two-Dimensional Array from user
Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by
reference. When declaring a two-dimensional array as a formal parameter, we can omit the
size of the first dimension, but not the second; that is, we must specify the number of columns.
For example:
void print(int A[ ][3], int N, int M)
In order to pass to this function an array declared as:
int arr[4][3];
the call is written like this:
print(arr);
Example:
27
POINTER
In C++, a pointer refers to a variable that holds the address of another variable. Like regular
variables, pointers have a data type. For example, a pointer of type integer can hold the address
of a variable of type integer. A pointer of character type can hold the address of a variable of
character type.
A pointer is a symbolic representation of a memory address. With pointers, programs can
simulate call-by-reference. They can also create and manipulate dynamic data structures. In
C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed
by another variable.
Addresses in C++
To understand C++ pointers, you must understand how computers store data.
When you create a variable in your C++ program, it is assigned some space the computer
memory. The value of this variable is stored in the assigned location.
To know the location in the computer memory where the data is stored, C++ provides
the & (reference) operator. The operator returns the address that a variable occupies.
For example, if x is a variable, &x returns the address of the variable.
Code Explanation:
1. Import the iostream header file. This will allow us to use the functions defined in the
header file without getting errors.
2. Include the std namespace to use its classes without calling it.
3. Call the main() function. The program logic should be added within the body of this
function. The { marks the beginning of the function's body.
4. Declare an integer variable x and assigning it a value of 27.
5. Declare a pointer variable *ip.
6. Store the address of variable x in the pointer variable.
7. Print some text on the console.
8. Print the value of variable x on the screen.
9. Print some text on the console.
10. Print the address of variable x. The value of the address was stored in the variable ip.
11. Print some text on the console.
12. Print value of stored at the address of the pointer.
13. The program should return value upon successful execution.
14. End of the body of the main() function.
29
NULL Pointer
If there is no exact address that is to be assigned, then the pointer variable can be assigned a
NULL. It should be done during the declaration. Such a pointer is known as a null pointer. Its
value is zero and is defined in many standard libraries like iostream.
Example :
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}
Output:
Code Explanation:
1. Declare a pointer variable ip and assigning it a value of NULL.
2. Print value of pointer variable ip alongside some text on the console.
3. The program must return value upon successful completion.
4. End of the body of the main() function.
Pointers of Variables
With C++, you can manipulate data directly from the computer's memory.
The memory space can be assigned or re-assigned as one wishes. This is made possible by
Pointer variables.
Pointer variables point to a specific address in the computer's memory pointed to by another
variable.
It can be declared as follows:
int *p;
Or,
int* p;
Example
#include <iostream>
30
return 0;
}
Output:
Code Explanation:
1. Declare a pointer variable p and a variable x with a value of 30.
2. Assign the address of variable x to p.
3. Print the value of pointer variable p alongside some text on the console.
4. The program must return value upon successful completion.
5. End of the body of the main() function.
Application of Pointers
Functions in C++ can return only one value. Further, all the variables declared in a function
are allocated on the function call stack. As soon as the function returns, all the stack variables
are destroyed.
Arguments to function are passed by value, and any modification done on the variables doesn't
change the value of the actual variables that are passed. Following example helps illustrate this
concept:-
Example 5:
#include <iostream>
test(&a, &b);
31
*n1 = 10;
*n2 = 11;
}
Output:
Code Explanation:
1. Create a prototype of a function named test that will take two integer parameters.
2. Call the main() function. We will add the program logic inside its body.
3. Declare two integer variables a and b, each with a value of 5.
4. Print some text on the console. The endl (end line) will move the cursor to begin
printing in the next line.
5. Print the value of variable a on the console alongside other text. The endl (end line) will
move the cursor to begin printing in the next line.
6. Print the value of variable b on the console alongside other text. The endl (end line)
will move the cursor to begin printing in the next line.
7. Create a function named test() that takes in the addresses of variable a and b as the
parameters.
8. Print some text on the console. The \n will create a new blank line before the text is
printed. The endl (end line) will move the cursor to begin printing in the next line after
the text is printed.
9. Print the value of variable a on the console alongside other text. The endl (end line) will
move the cursor to begin printing in the next line.
10. Print the value of variable b on the console alongside other text. The endl (end line)
will move the cursor to begin printing in the next line.
11. The program must return value upon successful completion.
12. End of the body of the main() function.
13. Defining the function test(). The function should take two integer pointer variables *n1
and *n2.
14. Assigning the pointer variable *n1 a value of 10.
15. Assigning the pointer variable *n2 a value of 11.
16. End of the body of the function test().
Even Though, new values are assigned to variable a and b inside the function test, once the
function call completes, the same is not reflected in the outer function main.
32
Using pointers as function arguments helps to pass the variable's actual address in the function,
and all the changes performed on the variable will be reflected in the outer function.
In the above case, the function 'test' has the address of variables 'a' and 'b.' These two variables
are directly accessible from the function 'test', and hence any change done to these variables
are reflected in the caller function 'main.'
Summary:
A pointer refers to a variable holding address of another variable.
Each pointer has a valid data type.
A pointer is a symbolic representation of a memory address.
Pointers allow programs to simulate call-by-reference and create and manipulate
dynamic data structures.
Arrays and pointers use a related concept.
The array name denotes the array's base.
If you want to assign the address of an array to a pointer, don't use an ampersand (&).
If there is no specific address to assign a pointer variable, assign it a NULL.
33
OBJECT ORIENTED PROGRAMMING CONCEPTS
There are two common programming methods: procedural programming and object-oriented
programming (OOP).
In a procedural program data is typically stored in a collection of variables and there is a set
of functions that perform operations on the data. The data and the functions are separate
entities. Usually the variables are passed to the functions that perform the desired operations.
The focus of procedural programming is on creating the functions, or procedures, that operate
on the program’s data. Procedural programming works well. However, as programs become
larger and more complex, the separation of a program’s data and the code that operates on the
data can lead to problems.
The object oriented programming design models the real world well and overcomes the
shortcomings of procedural paradigm. It views a problem in terms of objects and thus
emphasizes on both procedures as well as data.
An object is an entity that combines both data and procedures in a single unit. An object’s data
items, also referred to as its attributes, are stored in member variables. The procedures that an
object performs are called its member functions. This wrapping of an object’s data and
procedures together is called encapsulation.
Not only objects encapsulate associated data and procedures, they also permit data hiding.
Data hiding refers to an object’s ability to hide its data from code outside the object. Only the
object’s member functions can directly access and make changes to the object’s data.
Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object orientation
contributes to the solution of many problems associated with the development and quality of
software products. The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost. The principal advantages are:
• Through inheritance, we can eliminate redundant code by the use of existing classes.
34
• Build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development
time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that cannot be
invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables programmers to capture more detail of a model
and its implemental form.
• Object-oriented system can be easily upgraded from small to large system.
• Software complexity can be easily managed.
Application of OOP
OOP has become one of the programming buzzwords today. Applications of OOP are
beginning to gain importance in many areas. The most popular application of object-oriented
programming, up to now, has been in the area of user interface design such as window.
Hundreds of windowing systems have been developed, using the OOP techniques. Real-
business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it can
simplify a complex problem. The promising areas of application of OOP include:
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and Expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
35
Class & Objects
One of the major features of C++ is classes. They provide a method of binding together data
and functions which operate on them. Like structures in C, classes are user-defined data types.
The mechanism that allows you to combine data and the function in a single unit is called a
class. Once a class is defined, you can declare variables of that type. A class variable is called
object or instance. In other words, a class would be the data type, and an object would be the
variable.
A class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are
their properties.
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.
Keywords
Inline Functions: - An inline function is expanded in the line where it is invoked.
Member Function:- Private means that they can be accessed only by the functions
within the class.
Classes:- When you create the definition of a class you are defining the attributes and
behavior of a new type.
36
Objects:- Declaring a variable of a class type creates an object. You can have many
variables of the same type (class).
Classes are generally declared using the keyword class, with the following format:
class class_name {
private:
members1;
protected:
members2;
public:
members3;
};
Where class_name is a valid identifier for the class. The body of the declaration can contain
members that can be either data or function declarations. The members of a class are classified
into three categories: private, public, and protected. Private, protected, and public are reserved
words and are called member access specifiers. These specifiers modify the access rights that
the members following them acquire.
Private members of a class are accessible only from within other members of the same
class. You cannot access it outside of the class.
Protected members are accessible from members of their same class and also from
members of their derived classes.
Public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all
its members. Therefore, any member that is declared before one other class specifier
automatically has private access.
Example:
class Circle
{
private:
double radius;
public:
void setRadius(double r)
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
};
Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for declaring an object
is the same as that for declaring any other variable. The following statements declare two
objects of type circle: Circle c1, c2;
38
void Circle :: setRadius(double r)
{
radius = r;
}
The following program demonstrates the general feature of classes. Member functions
setRadius() and getArea() defined outside the class.
#include <iostream>
using namespace std;
class Circle //specify a class
{
private :
double radius; //class data members
public:
void setRadius(double r);
double getArea(); //member function to return area
};
void Circle :: setRadius(double r)
{
radius = r;
}
double Circle :: getArea()
{
return 3.14 * radius * radius;
}
int main() {
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout << c1.getArea(); //display area of circle object
return 0;
}
REFERENCE
1. Kyle Loudon. (2003). C++ Pocket Reference. O'Reilly Media; 1st edition, ISBN-
13 : 978-0596004965.
2. Stanley Lippman, Josée Lajoie, Barbara Moo. (2012). C++ Primer. Addison-Wesley
Professional; 5th edition, ISBN-13: 978-0321714114
3. Scott Meyers. (2014). Effective Modern C++: 42 Specific Ways to Improve Your Use of
C++11 and C++14. O'Reilly Media, Incorporated; 1st edition, ISBN-13 : 978-
1491903995
4. Dale, N. et al (2002). Programming and Problem Solving with C++ (3rd ed). Jones and
Bartlett Publishers. ISBN: 0763721034
39