Unit1Notes Part 1
Unit1Notes Part 1
Contents:
What is object oriented programming? Why do we need object-oriented Programming?
Application and Characteristics of object oriented languages. Basic concepts of Object Oriented
Programming: Encapsulation, Abstraction, Inheritance, Polymorphism, Dynamic Binding,
Message Passing, class and object. Structure of C++ program, Compiling and Executing C++
Programs. Classes: Specifying Class, Access Specifies, Defining Data member and member
function. Objects: Creating Object, memory allocation for object, Operators in C++: The Scope
resolution operator, The arrow operator, memory management operator, type casting, Pointer to
object, The 'this' pointer, Objects and Arrays: Array of Objects, Arrays inside objects.
Namespaces, Nested/Inner Classes.
Characteristics of POP:
1) It emphasis on doing things i.e. Algorithm.
2) Large programs are divided into smaller program known as function.
3) Most of the function shares global data.
4) Data move openly around the system from function to function.
5) Function transforms data from one form to another.
6) It follows top down approach in program design.
Features of OOP:
1) It emphasis on data rather than procedure.
2) Programs are divided into objects.
3) Objects are characterized by functions that operate on data.
4) Functions that operate on data of the object are tied together in data structure.
5) Data is hidden and cannot be access by external function.
6) Object communicates with each other through function.
7) New data and function can be easily added whenever necessary.
8) It follows bottom up approach in program design.
2) Class :
The building block of C++ that leads to Object-Oriented programming is a Class.
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 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 group of objects with similar attributes and common relationship to other
objects i.e. class is collection of objects of similar type. Objects are variables of type
class. Classes are user define data types and behaves like any other built-in type. Once a
class is defined we can create any number of objects belonging to that class.
3) Data Abstraction and Encapsulation :
The wrapping of data and functions into a single unit (class) is called as encapsulation.
The data is not accessible to the outside world and only the function of that class can
access its data. This insulation of data from direct access by a program is called data
hiding or information hiding. Abstraction refers to the act of representing essential
features without including the background details. Classes use the concept of abstraction
and encapsulate all essential properties of objects that are to be created. The attributes are
sometime called as data members and the functions that operate on these data are called
as methods or member function. Classes are also known as Abstract Data Types (ABT)
as they uses concept of data abstraction.
4) Inheritance :
It is the process by which objects of one class acquire the properties of objects of another
class. It also means defining a new objects in terms of old one. It gives the idea of
reusability. One class of object inherits (reuse) data and behavior from another class, and
thus form hierarchy among classes in which child class is inheritaed from its parent class.
Parent class is called as base class and child class is called as derived class. Base class
also known as super class and derive class as sub class. Thus we can add additional
features to an existing class without modifying it. OOP’s also support multiple
inheritance which means class can be derived from more than one base class. In fig. 1.4
Class Bird is Base class. Flying Birds and Non-flying Birds are child classes.
5) Polymorphism :
It means ability to take more than one form. It refers to single operation can have
different behavior in different object i.e. different object react differently to same
message where behavior depends upon types of data used for operation.
e.g. Operation of addition : It will generate a sum if data is two number. If data is string,
operation will produce a third string by concatenation operation.
Advantages of OOP:
OOP focuses on identifying objects from application and writing procedures around those
objects. Following are advantages of OOPs.
1) By using inheritance we can eliminate a redundant code and extend use of existing class.
2) Encapsulations helps to built a protected program that cannot be access by other parts of
program.
3) One can have multiple objects without any interference.
4) We can divide program classes and objects.
5) Interference with external system is simple by using message passing.
6) It supports reusability, which reduces design, coding and testing cost of software.
7) OOPs system can be easily upgraded from small to large system.
8) Software complexity can be easily managed.
Application of C++:
1) Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
2) While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
3) 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.
Application of OOP:
The promising areas of application of OOP include:
1) Real-time system
2) Simulation and modeling
3) Object-oriented data bases
4) Hypertext, Hypermedia, and expertext
5) AI and expert systems
6) Neural networks and parallel programming
7) Decision support and office automation systems
8) CIM/CAM/CAD systems
1) Comments :
(// - double slash) is a new comment symbol. It may start anywhere in the line and
whatever follows till the end of line is ignore. It is basically single line comment and
multi-line comment can be written as follows
// This is example
// of C ++ prg.
The comment symbol of C is (/* */) is still valid in C ++
2) Output Operator :
cout << “Hello”;
Above statement displays a string in quotation marks on the screen. Cout is a identifier
and is predefined object that represents standard output in C ++. The output can be
redirected to other output devices also. The operator ‘<<’ is called as ‘insertion’ or ‘put
to’ operator. It inserts (sends) the content of variable on its right to the object on its left.
Printf statement can also be use for displaying output in C ++.
Fig: Output using Insertion operator
3) iostream File :
# include <iostream.h>
# include directive causes the pre-processor to add the contents of iostream file to the
program. For example this file contain declaration for the identifier as ‘cout’ and ‘cin.’ and
operator <<,>>.
4) Return type of main :
In C ++, main () returns integer type values. Therefore every main () in C++ should end
with ‘return’ statement and return type for main should be explicitly specified as int.
Otherwise program will give a warning.
5) Variables :
All the variables of program must be declared before they are used in program e.g. int
a,b,c;
6) Input operator :
The statement cin >>number; a is called as input statement. It causes program to wait for
a user to type a number. The number entered is placed in variable ‘a’. The identifier cin is
pre-defined object that represents standard input stream. Here input stream represents
keyboard. The operator >> is called as extraction or ‘get from’ operator. It extracts
(takes) value from keyboard and assigns it to the variable on its right.
Sample Program 1 :
Write a program to accept radius from user and find out area of circle.
# include <iostream.h>
void main ()
{
float r, area, pi;
clrscr ( );
cout << “enter the radius of circle to find the area of that circle”;
cin >> r;
pi = 3.14;
area = pi * r * r;
cout << “area of circle =” << area;
getch ();
This approach is based on the concept of client-server model as shown in following fig. The
class definition including the member functions constitute the server that provides services to the
main program known as client. The client uses the server through the public interface of the
class.
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected,
public, register, einterpret_cast, return, short, signed, sizeof, static, static_cast, struct,
switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while
Identifiers :
- Identifiers Simply references to memory locations, which can hold values (data).
- To put in other words Identifiers refers to names of variables, functions, arrays, classes
etc. created by programmer.
- Are formed by combining letters (both upper and lowercase), digits (0–9) and
underscore ( _).
The C++ language is a "case sensitive" language. That means that an identifier written in capital
letters is not equivalent to another one with the same name but written in small letters. Thus, for
example, the RESULT variable is not the same as the result variable or the Result variable.
These are three different variable identifiers.
Constants:
Constants refer to the fixed values that do not change during the execution of the program. C++
supports several kinds of literal constants. They include characters, floating point numbers and
strings.
Example:
To declare a constant, use keyword const as shown in the following variable declaration
example:
const int day_in_week = 7;
const float total_loan = 1100000.35;
Variables :
- Identifier that value may change during the program execution.
- Every variable stored in the computer’s memory has a name, a value and a type.
- All variable in a C / C++ program must be declared before they can be used in the
program.
- A variable name in C / C++ is any valid identifier, and must obey the rules mentioned
above.
Initializing a variable means, give a value to the variable, that is the variable’s initial
value and can be changed later on.
- Variable name are said to be lvalue (left value) because they can be used on the left side
of an assignment operator.
- Constant are said to be rvalue (right value) because they only can be used on the right
side of an assignment operator. For example:
x = 20;
x is lvalue, 20 is rvalue.
Note that lvalue can also be used as rvalue, but not vice versa.
General form:
data_type variable_name;
Example of the variable declaration
int m, n;
float total, rate;
char user_response;
char color[7];
n = 20;
rate = 4.5;
user_response = ‘n’;
color = "green";
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. So we need to declare a data type so that computer can allocate required
memory to it. Data types in C++ can be classified under various catagories as shown in following
figure of Hierarchy of data types.
Figure: Hierarchy of data types.
Built-in data types are also known as Basic data types or Fundamental data types.
Basic data type (int, char and float) and their the range of values that can be
represented with each one are shown in Table :
C++ Operators:
1. Basic Operators:
All basic operators of C works in c++ with same meaning and syntax
a. Assignment (=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a.
a = b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue).
b. Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
They increase or reduce by one the value stored in a variable. They are equivalent to +=1 and
to - =1,
e.g a++;
b--;
d. Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and
equality operators
f. Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true
and a different one if the expression is evaluated as false. Its format is:
condition ? result1 : result2
e.g (a>b) ? a : b;
g. sizeof() operator
This operator accepts one parameter, which can be either a type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
a = sizeof (int);
This will assign the value 2 to a because int is a two-byte long type.
The operator (::, two colons) is called as scope resolution operator. It is used to define a member
of a class from outside the class definition itself. The scope operator (::) specifies the class to
which the member being declared belongs, This operator helps in defining the member function
outside the class.
The syntax for a member function definition outside the class definition is :
Eg.
Void SYIT :: getdata()
{ // body of function
}
‘new’ Operator:
General form:
pointer = new datatype;
It returns a pointer to the beginning of the new block of memory allocated.
The difference between declaring a normal array and assigning dynamic memory to a Pointer:
The most important difference is that the size of an array has to be a constant value, which limits
its size to what we decide at the moment of designing the program, before its execution, whereas
the dynamic memory allocation allows us to assign memory during the execution of the program
(runtime) using any variable or constant value as its size.
‘delete’ Operator:
Since the necessity of dynamic memory is usually limited to specific moments within a program,
once it is no longer needed it should be freed so that the memory becomes available again for
other requests of dynamic memory. This is the purpose of the operator delete.
General format is:
delete pointer;
delete [] pointer;
The first expression should be used to delete memory allocated for a single element, and the
second one for memory allocated for arrays of elements.
The value passed as argument to delete must be a pointer to a memory block previously
allocated with new operator.
e.g delete p ;
Where, ‘class’ is keyword used to define class as data type. name_of _class is user
defined name for the class.
e.g
class SYIT
{
private:
int Roll;
char name[20];
public:
void getdata();
void putdata();
};
Creating object of a class (DECLARATION OF OBJECTS )
The objects of a class are declared after the class definition. One must remember that a class
definition does not define any objects of its type, but it defines the properties of a class. For
utilizing the defined class, we need variables of the class type (i.e. object).
Once class is defined, we can create object later in main function as :
Syntax: Class_name object _name;
e.g. void main()
{ SYIT S1;
---
----
}
Where S1 is said to be object of class SYIT.
Objects can also be created immediately when class is defined by placing object name after class
closing brace and before semicolon as:
class class_name
{ -----
-----
}objectname;
For example,
class SYIT
{
Private:
int Roll;
char name[20];
public:
void getdata();
void putdata();
}s1;
The code of the function is same in both the cases, but the function header is different as
explained below :
a) Defining Member Function Inside Class Definition
One can replace function declaration by actual function definition inside class
as shown in following example
class SYIT
{ private:
int rollno :
public;
void getdata ( )
{ cout << “enter your Roll no”;
cin >> rollno;
}
} x;
When function is define inside a class as above example is treated as inline function.
Normally small function is defined inside class.
main ( )
{
// body of main function
}
‘SYIT :: ’ is also called as membership label and the operator ‘::’ is called as scope resolution
operator.
Example program using class:
1. WAP to create a class SYIT having data members as Roll and name. Accept this data and
display for one object of class. Define member function outside of class.
#include<iostream.h>
#include<conio.h>
class SYIT // class definition
{
private:
int Roll;
char name[20];
public:
void getdata(); // function declaration
void putdata(); // function declaration
}s1; // end of class
void main ( )
{
clrscr(0;
s1.getdata(); // function call
s1.putdata(); // function call
getch();
}
2. WAP to create a class SYIT having data members as Roll and name. Accept this data
and display for one object of class. Define member function inside of class.
#include<iostream.h>
#include<conio.h>
class SYIT // class definition
{
private:
int Roll;
char name[20];
public:
void getdata ( ) //function definition inside class
{
cout << “enter your Roll no and name : ”;
cin >> Roll>>name;
}
void main ( )
{
clrscr(0;
s1.getdata(); // function call
s1.putdata(); // function call
getch();
A private member variable or function cannot be accessed, or even viewed from outside the
class. Only the class and friend functions can access private members. By default all the
members of a class would be private, for example in the following class width is a private
member, which means until you label a member, it will be assumed a private member –
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so that they
can be called from outside of the class as shown in the following program.
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
In C++, all the member functions of a class are created and stored when the class is defined and
this memory space can be accessed by all the objects related to that class.
Memory space is allocated separately to each object for their data members. Member variables
store different values for different objects of a class.
The figure shows this concept.
Eg:
class SYIT
{ private:
int roll;
char name[20];
public:
void getdata();
void putdata();
}s1,s2;
From above example:
Memory allotted for data variables:
Then memory allotted to object s1 :
roll name
Again separate memory allotted to roll and name for object s2:
roll name
getdata()
Memory for object s1 as well s2.
ARRAY OF OBJECTS:
Each class has it’s own object. i.e. we can have variable of type class. In a same way we can have
array of variable of the type class such variable are called as array of an object. The syntax for
declaring and using object array is same as it is for any other type of array.
Array of object of class is created in same way as single object of class is created as:
Syntax:
class class_name
{ -----
-----
} objectArrayname[size];
e.g
class SYIT
{ ---
-----
} S[5];
Generally it is used when we need more than one object for a same class.
Example Program:
1) To accept and display roll no and name of 3 students, following program uses array of three
objects.
#include<iostream.h>
#include<conio.h>
class SYIT
{ provate:
int Roll_no;
char name [20];
public :
void getdata ( );
void displaydata ( );
} stud [3];
main ()
{ int i;
for (i = 0; i < 3; i++) //Accept data 3 times
{
stud(i).getdata(); // function call
}
{
stud(i).displaydata(); // function call
getch();
return(0);
}