Object Oriented Proramming Notes 1
Object Oriented Proramming Notes 1
In the procedure oriented approach, the problem is viewed as sequence of things to be done such
as reading , calculation and printing. Procedure oriented programming basically consist of
writing a list of instruction or actions for the computer to follow and organizing these instruction
into groups known as functions. Examples are
C
Fortran
Pascal
COBOL
BASIC
ALGOL
3. No data hiding
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. The fundamental
idea behind object oriented approach is to combine both data and function into a single unit and
these units are called objects.
The term objects means a combination of data and program that represent some real word entity.
For example: consider an example named JOHN; JOHN is 25 years old and his salary is 2500.
The JOHN may be represented in a computer program as an object. The data part of the object
would be (name: John, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrive of data, change age,
change of salary). In the John object the name, age and salary are called attributes of the object.
BENEFITS OF OOP:
Oop offers several benefits to both the program designer and the user. Object-oriented
contributes to the solution of many problems associated with the development and quality of
software products. The principal advantages are :
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. This principle of data hiding helps the programmer to build secure programs that can‘t be
invaded by code in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist without any interference.
5. It is easy to partition the work in a project based on objects.
6. Object-oriented systems can be easily upgraded from small to large systems.
APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user interface design
such as windows. There are hundreds of windowing systems developed using oop techniques.
Real business systems are often much more complex and contain many more objects with
complicated attributes and methods. Oop is useful in this type of applications because it can
simplify a complex problem. The promising areas for application of oop includes.
1. Real – Time systems.
RTS are considered to be systems whose behavior depends on the time elapsed, since
they start processing data entries until the outputs are known. One of the most important
features is that the response time of these systems must be predictable and limited.
2. Simulation and modeling
is the use of a physical or logical representation of a given system to generate data and
help determine decisions or make predictions about the system
Hypertext, hypermedia, and expertext are all related concepts, but they have different nuances.
Hypertext is a system of interlinking nodes of text. Nodes can be anything from a single word to
a paragraph or even a whole document. The nodes are linked together using hyperlinks, which
are typically underlined or blue words or phrases
Hypermedia is an extension of hypertext that includes non-text elements, such as images, audio,
video, and animations
Expertext is a type of hypermedia that is designed to provide users with expert knowledge on a
particular topic. Expertext systems are used in a variety of settings, including education, training,
and customer support.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Dicision support and office automation systems.
7. namespace:
namespace is used to define a scope that could hold global identifiers. ex:-namespace scope for
c++ standard library. classes ,functions and templates are declared within the namespace named
std using namespace std;-->directive can be used.
user defined name space:
syntax for defining name space is
namespace namespace_name
{ //declarations of variables.functions,classes etc...
}
C++ Comments:
C++ introduces a new comment symbol //(double slash). Comments start with a double slash
symbol and terminate at the end of line.
A comment may start anywhere in the line and whatever follows till the end of line is ignored.
Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multi line comments can be
written as follows:
// this is an example of
// c++ program
// thank you
Output Operator:
The statement cout <<‖Hello, world‖ displayed the string within quotes on the screen. The
identifier cout can be used to display individual characters, strings and even numbers.
It is a predefined object that corresponds to the standard output stream. Stream just refers to a
flow of data and the standard Output stream normally flows to the screen display. The cout
object, whose properties are defined in iostream.h represents that stream. The insertion operator
<< also called the ‗put to‘ operator directs the information on its right to the object on its left.
Input Operator:
The statement
cin>> number 1;
Return Statement:
In C++ main ( ) returns an integer type value to the operating system. Therefore every main (
) in C++ should end with a return (0) statement, otherwise a warning or an error might occur.
The return statement causes the main function to finish. return may be followed by a return code
(in our example is followed by the return code 0). A return code of 0 for the main function is
generally interpreted as the program worked as expected without any errors during its execution.
This is the most usual way to end a C++ console program.
You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and, finally line with
statements (like the insertion into cout), which were all included within the block.
TOKENS:
The smallest individual units in a program are known as tokens. C++ has the following tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
KEYWORDS:
The keywords implement specific C++ language feature. They are explicitly reserved identifiers
and can‘t be used as names for the program variables or other user defined program elements.
IDENTIFIERS:
Identifiers refers to the name of variable , functions, array, class etc. created by programmer.
Each language has its own rule for naming the identifiers. These are user defined names
consisting of sequence of letters and digits
The following rules are common for both C and C++.
In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
Example: ab Ab aB AB are treated differently
Variables
A variable is an identifier which is used to store a value.
Variables are containers for storing data values, like numbers and characters.
variables must be declared before they can be used. This tells the compiler how to work with the
variable and tells the linker how much space needs to be allocated for it.
A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
the underscore character.
The first character must be a letter or underscore.
Blank spaces cannot be used in variable names.
Special characters like # and $ are not allowed.
C++ keywords cannot be used as variable names.
Variable names are case-sensitive.
Variable declaration
A Variable Declaration means that the programmer writes some instructions to tell the compiler
to create the storage in a memory location. The syntax for defining variables is:
Syntax:
data_type variable_name;
Variables are declared in the above example, but none have been assigned any value. Variables
can be initialized, and initial values can be set along with their declaration.
Syntax:
Example:
float area;
double d;
/* actual initialization */
width = 10;
area = 26.5;
#include <iostream>
int main()
int x = 5;
int y = 2;
int Result;
Result = x * y;
An operator is a symbol which represents a particular operation that can be performed on data.
An operand is the object on which an operation is performed. By combining the operators and
operands we form an expression.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
8. unary operator
9. Special operators
i)Local scope
ii)Global scope
Global scope: visibility of a variable to all functions of a program Scope resolution operator in
―::‖ . This is used to access global variables if same variables are declared as local and global
Like C,C++ is also a block-structured language. Block -structured language. Blocks and scopes
can be used in constructing programs. We know same variables can be declared in different
blocks because the variables declared in blocks are local to that function. Blocks in C++ are
often nested
the global version of a variable can't be accessed from with in the inner block. C++ resolves this
problem by introducing a new operator :: called the scope resolution operator .This can be used
to uncover a hidden variable.
Syntax:
: : variable –name;
Example
#include<iostream>
using namespace std;
int m=10;
main()
{
int m=20;
{
int k=m;
int m=30;
cout<<‖we are in inner block‖;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<‖\n we are in outer block \n‖;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
A class member pointer can be declared using the operator :: * with the class name. We
can define a pointer to the member m of class ABC as follows :
Assignment
example
2. Pointer to member operator ->*,->
Let us assume that ―A‖ is an object of ―ABC‖ declared in a main function . We can
access ―m‖ using the pointer ip as follows.
#include<iostream>
using namespace std;
class sample
{
public:
int x;
void display()
{
cout<<"x="<<x<<endl;
}
};
int main()
CONSTANTS:
Constants refer to values that do not change during the execution of a program. Constants can be
divided into two major categories:
1.Primary constants:
a)Numeric constants
Integer constants.
Floating-point (real) constants.
b)Character constants
2.Secondary constants:
Enumeration constants.
Symbolic constants.
Arrays, unions, etc.
1.Commas and blank spaces are not permitted within the constant.
2.The constant can be preceded by minus (-) sign if required.
3.The value of a constant must be within its minimum bounds of its specified data type.
Manipulators:
Manipulators are the operators used to format the data that is to be displayed on screen.The most
commonly
used manipulators are endl and setw
endl:-it is used in output statement and inserts a line feed. It is similar to new line character
(―\n‖)
ex:
………………..
cout<<‖a=2‖<<endl;
cout<‖name=sunil‖<<endl;
setw:-
this manipulator allows a specified width for a field that is to be printed on screen
and by default the value printed is right justified.This function is available in header file
iomanip.h
example
#include<iostream.h>
#include<iomanip.h>
using namespace std;
int main()
{
int s=123;
Control statements:-
The flow of execution of statements in a program is called as control. Control
statement is a statement which controls flow of execution of the program. Control statements are
classified into following categories.
1. Sequential control statements
2. Conditional control statements
3. Unconditional control statements
Sequential control statements ensures that the instructions(or statements) are executed in the
samorder in which they appear in the program. i.e. By default system executes the statements in
the program in sequential order.
Statements that are executed when a condition is true. These statements are divided into three
categories. they are
1.Decision making statements:- These statements are used to control the flow of
execution of a program by making a decision depending on a condition, hence they are
named as decision making statements.
Decision making statements are of four types
a. Simple if
b. if else
c. nested if else
d. If else ladder
example
/*largest of three numbers*/
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter a,b,c values:";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"A ia largest among three numbers\n";
cout<<"A= "<<a;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c= "<<c;
}
d) if else ladder
The nesting of if-else depends upon the conditions with which we have to deal.
The condition is evaluated from top to bottom.if a condition is true the statement
associated with it is executed.
When all the conditions become false then final else part containing default statements
will be executed.
Syntax
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
If for suppose we have more than one valid choices to choose from then we can use
switch statement in place of if statements.
syntax
switch(expression)
b) DO WHILE STATEMENT :
The while loop does not allow body to be
executed if test condition is false. The do while is an
exit controlled loop and its body is executed at least
once.
do
{
body
}while(test condition);
example
/*c program to find sum of n natural numbers */
#include<stdio.h>
int main()
{
int i = 1,sum = 0,n;
c)FOR LOOP :
It is also an entry control loop that provides a more concise structure
Syntax:
for(initialization; test expression; increment/decrement)
{
statements;
}
For statement is divided into three expressions each is separated by semi colon;
1.initilization expression is used to initialize variables
2.test expression is responsible of continuing the loop. If it is true, then the program
control flow goes inside the loop and executes the block of statements associated
with it .If test expression is false loop terminates
3.increment/decrement expression consists of increment
or decrement operator This process continues until test
condition satisfies.
Example
/*c ++ program to find sum of n natural numbers */
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
for(i=1;i<=n;i++)
{
Nested loops:
Writing one loop control statement within another loop control statement is called nested
loop
Statement
Ex:
for(i=1;i<=10;i++)
for(j=1;j<=10;j++)
cout<<i<<j;
example
1.goto :- goto statement is used for unconditional branching or transfer of the program
execution to the labeled statement.
example
/*c program to find sum of n natural numbers using goto statement*/
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;
break:-
when a break statement is encountered within a loop ,loop is immediately exited and the
program continues with the statements immediately following loop.
Example
/*c++ program to find sum of n natural numbers example use of break statement*/
#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<"Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;
i++;
if(i>n) break;
goto L1;
cout<<"Sum of first‖<<n<<‖natural numbers is:"<<sum;
return 0;
}
Continue:
It is used to continue the iteration of the loop statement by skipping the statements
after continue statement. It causes the control to go directly to the test condition and then
to continue the loop.
The class declaration describes the type and scope of its members. The class
function
definition describes how the class functions are implemented.
a) Class declaration
Syntax:-
1.Private:
If the data members are declared as private access then they cannot be accessed
from other functions outside the class. It can only be accessed by the functions
declared within the class. It is declared by the key word „private‟ .
2.public:
If the data members are declared public access then they can be accessed from
other functions outside the class. It is declared by the key word „public‟ .
3.protected:
The access level of protected declaration lies between public and private. This
access
specifier is used at the time of inheritance
Note:- If no access specifier is specified then it is treated by default as private
Example:
#include<iostream>
using namespace std;
class student
{
//private:
int sid;
char sname[20];
public:
void getdata()
{
cout<<"Enter STUDENT ID : ";
cin>>rollno;
cout<<"Enter STUDENT NAME : ";
cin>>sname;
}
void putdata()
OBJECTS
An object is said to be an instance of a class. Defining an object is similar to
defining a variable of any data type: Space is set
aside for it in memory. Defining objects in this way means creating them. This is
also called instantiating them. Once a Class has been declared, we can create
objects of that Class by using the class Name like any other built-in type variable.
syntax :
class_name object_name;
Ex:
student s;
Method 1:
We will create the objects in main() as follows:
Syntax:
classname objectname;
Example:
Employee e1;
Method2:
We can create the objects at time of class declaration itself
That is, Objects can also be created when a class is declared by placing their
names
immediately after the closing brace as follows.
Syntax:
class classname
{
Datamembers;
Member functions;
} objectnam1,objectname2,……objectname n;
Example:
Class Employee
{
int eid;
float salary;
} e1,e2,e3;
time
declaration of class.
class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.
An object can be declared in the main(), and member functions are declared in
class in
public section so always a member function can be called by using object.
The object can access the public data member and member functions of a class by
using dot(.) and arrow(->) operators.
syntax:
[object name] [operator] [Member name]
Example
class xyz
{
Int x;
Int y;
public:
int z;
};
---------
----------
xyz p;
p. x =0; //error . x is private
p, z=10; //ok ,z is public
Example:
class item
{
Int number;
float cost;
public:
void getdata (int a ,float b);
void putdata(void)
{
cout<<number<<endl; cout<<cost<<endl;
}
};
This is used to access global variables if same variables are declared as local and global
#include<iostream.h>
int a=5;
void main()
{
int a=1;
cout<<‖Local a=‖<<a<<endl;
cout<<‖Global a=‖<<::a<<endl;
}
return_type class_name::function_name(parameters)
function_body;
Example
#include <iostream>
class Example
private:
int val;
public:
void print_val();
};
//function definitions
void Example::init_val(int v)
{ val=v;
void Example::print_val()
cout<<"val: "<<val<<endl;
int main()
//create object
Example Ex;
Ex.init_val(100);
Ex.print_val();
return 0;
Example 2
#include<iostream>
class item
int number;
float cost;
public:
cout<<"number:"<<number<<endl;
cout<<"cost :"<<cost<<endl;
};
number=a;
cost=b;
int main()
item x;
x.getdata( 100,299.95);
item y;
y.getdata(200,175.5);
y.displaydata();
A member function can be called by using its name inside another member function of the same
class. This is known as nesting of member functions.
Example
#include<iostream>
class set
int m,n;
public:
int input(void);
void display(void);
int largest(void);
};
int set::largest(void)
if(m>n)
return m;
else
return n;
int set::input(void)
cin>>m>>n;
return 0;
void set::display(void)
cout<<"largest value="<<largest()<<"\n";
int main()
set A;
A.input();
A.display();
largest value= 30
It is initialized to zero when the first object of its class is created. No other initialization is
permitted. It is initialized before any object of this class is created, even before the main
starts.
Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
It is visible only within the class, but its lifetime is the entire program.
Static data member is defined by keyword „static‟
Syntax:
Data type class name::static_variable Name;
Ex: int item::count;
Example
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
A static function can have access to only other static members (functions or variables)
declared in the same class.
A static member function is to be called using the class name (instead of its objects) as
follows: class-name :: function-name;
example
#include<iostream.h>
class test
{
int code;
static int count;
public:
class Student {
// static member
// Constructor called
Student()
total += 1;
};
int Student::total = 0;
int main()
// Student 1 declared
Student s1;
// Student 2 declared
Student s2;
// Student 3 declared
Student s3;
return 0;
output
Number of students:1
Number of students:
FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non
member function cannot have an access to the private data of a class. In C++ a non
member function can access private members by making the function friendly to a class.
Definition:
A friend function is a function which is declared within a class and is defined outside the
class.
It does not require any scope resolution operator for defining . It can access private
members of a class. It is declared by using keyword “friend”
A function or an entire class may be declared to be a friend of another class.
A friend of a class has the right to access all members (private, protected or public) of the class
class A
{
friend class B; // Class B is a friend of class A private:
// private members of A
int i;
float f;
public: // public members of A
void getdata(int a);
};
class B{ // Class B
int j;
A friend function has the right to access all members (private, protected or public) of the class.
example
#include<iostream>
using namespace std;
class base {
int val1, val2;
public:
void get() {
cout << "Enter two values:";
cin >> val1>>val2;
}
friend float mean(base ob);
};
int main() {
base obj;
INLINE FUNCTIONS:
Definition:
An inline function is a function that is expanded in line when it is invoked.
Inline expansion makes a program run faster because the overhead of a function call and
return is eliminated. It is defined by using key word ―inline‖
General Form:
inline function-header
{
function body;
}
example
#include<iostream>
using namespace std;
inline float mul(float x, float y)
{
return (x*y);
}
inline double div(double p, double q)
{
return (p/q);
}