CHAPTER 1
PRINCIPLES OF OBJECT ORIENTED PROGRAMMING
PROCEDURE ORIENTED PROGRAMMING VS OBJECT ORIENTED PROGRAMMING
Q] Write Down the difference between POP and OOP? [4 M]
PROCEDURE ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING
1. Focus is on procedure (algorithms). 1. Focus is on data.
2. Large programs are divided into multiple 2. Programs are divided into multiple
functions. objects.
3. Most of the functions share global data. Data 3. Data is hidden and cannot be accessed
is not hidden. by external functions.
4. Data move openly around the system from 4. Treats data as a critical element in
function to function. Functions transform data program development and does not allow
from one form to another by calling each other. it to flow freely around the system.
5. Employs top-down approach in program 5. Employs bottom-up approach in
design. program design
6. It does not model real world problems very 6. It is used to model real life entities in
well. system design.
7. Procedure oriented approach is used in C 7. Object oriented approach is used in C++
language. language.
Q] Write down the Properties of POP. [2 M]
1. Focus is on procedure (algorithms).
2. Large programs are divided into multiple functions.
3. Most of the functions share global data. Data is not hidden.
4. Data move openly around the system from function to function. Functions transform
data from one form to another by calling each other.
5. Employs top-down approach in program design.
6. It does not model real world problems very well.
7. Procedure oriented approach is used in C language.
PROPERTIES OF OBJECT ORIENTED PROGRAMMING
Q] Write down the Properties of POP. [2 M]
1. Focus is on data.
2. Programs are divided into multiple objects.
3. Data is hidden and cannot be accessed by external functions.
4. Treats data as a critical element in program development and does not allow it to flow
freely around the system.
5. Employs bottom-up approach in program design
6. It is used to model real life entities in system design.
7. Object oriented approach is used in C++ language.
BASIC CONCEPT OF OOP
Q] Explain Basic Concepts of Object Oriented Programming? [4 M]
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
1. OBJECT
Objects are the basic run-time entities in an OOP environment.
An object is an instance of a class.
An object consists of characteristics (attribute) and behavior (operation).
In OOP, the attributes of an object are represented by the variables and the operations
are represented by the functions.
2. CLASS
A class is a template or blueprints to create objects of similar type.
To create an object of a particular class, we need to specify the data member and member
function of that particular class.
In OOP, a class is a way of grouping objects having similar characteristics.
A class is a user-defined data type, which represents a group of similar objects.
Example:-
class Person
{
char Name[10];
int Age;
char City[20];
public:
void getdata( );
void putdata( );
};
Person Amol
Data Member: 42 Akshay
Name Pune
Age 34
789090190
City
Ahmednagar
Phone
Member Functions: 7756090190
display( )
Fig. (a) Class Definition Fig. (b) Objects of class person
3. ABSTRACTION
Data abstraction refers to the act of representing essential feature without including background
details or explanation.
Classes use the concept of abstraction and are defined as list of abstract attributes such as size,
weight, cost and functions to operate on these attributes.
The attributes are called as Data Members and the functions that operate on data are called as
Member Functions.
Since classes use the concept of abstraction, they are known as Abstract Data Types (ADT).
4. DATA ENCAPSULATION
Data Encapsulation means wrapping up of data and function that operate on data into a single
unit.
Classes use the concept of Encapsulation.
The data is not accessible to the outside world and only those functions which are wrapped in
the class can access it.
It is called Data Hiding or Information Hiding.
5. INHERITANCE
The process by which the object of one class acquires the properties of object of another
class is called Inheritance.
A Base Class / Parent Class
B Derived Class / Child Class
The new class is called as Derived class or Child class.
The old class is called as Base class/ Parent class.
6. POLYMORPHISM
Polymorphism means the ability to take more than one form.
In a programming language, Polymorphism refers to a function having the same name
but being used in different ways.
Fig. shows that a single function name can be used to handle different types of
arguments.
OBJECT ORIENTED PROGRAMMING LANGUAGES
Q] List Object Oriented Programming Languages?
1. Simula
2. Smalltalk
3. C++
4. Ada
5. Java
6. C#
APPLICATIONS OF OOP
Q] List Applications of Object Oriented Programming?
1. Real time systems
2. Simulation and modeling
3. Object Oriented databases
4. Hypertext, hypermedia and expertext
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
8. CAM/CAD systems
C vs C++
C C++
C language was developed by Dennis C++ language was developed by Bjarne Stroustrup
1
Ritchie in 1972 at AT&T Bell Laboratories in early 1980’s at AT&T Laboratories.
C language is a top-down structured C++ language is a bottom up object oriented
2
programming language. programming language.
When compared to C++, C is a subset of C++ is a superset of C. C++ can run most of C code
3 C++. while C cannot run C++ code.
C language programs are saved with .c C++ language programs are saved with .cpp
4
extension. extension.
In C language, scanf ( ) and printf( ) are
In C++ language, cin and cout are used as I/O
used as I/O functions. The header file
5 functions. The header file required to include for
required to include for this purpose is,
this purpose is, "iostream.h".
"stdio.h".
C language requires format specifier for C++ language does not require format specifier for
6
printing and scanning variables. printing and scanning variables.
7 Function driven language Object driven language
Does not support Function and operator
8 Supports Functions and Operator Overloading.
overloading
TOKENS
Tokens are the basic building blocks of C++ language which are constructed
together to write a C++ program.
C++ tokens are defined as the smallest individual unit in a program.
These tokens represent the individual entity of language. The following different
types of token are used in C++:
(a) Keywords,
(b) Identifiers,
(c) Constants and variables,
(d) Strings
(e) Operators
(f) Special Symbols
KEYWORDS
Keywords are also known as reserved words because the meaning of these words is
predefined to the compiler.
Every keyword is reserved for a specific purpose and hence cannot be used as a user
defined name (identifiers).
All keywords are in lower case.
Keywords are listed below
asm default float operator static_cast union
auto declare for private struct unsigned
break do friend protected switch using
bool double goto public template virtual
case dynamic if register this void
catch else inline reinterpret_cast throw volatile
char enum int return true wchar_t
class explicit long short try while
const export mutable signed typedef
const_cast extern namespace sizeof typeid
continue false new static typename
IDENTIFIERS
Identifiers are the names given to different user defined things like variable,
constants, functions, classes, objects, structures, unions etc.
Rules for constructing Identifiers
1. Identifiers can consist of alphabets, digits and a special symbol i.e. ‘_’ underscore.
2. Identifiers should not start with digit.
3. Identifiers are case sensitive so the max and MAX are considered as two
different identifiers.
4. An identifier should not contain special symbols, comma or blank space.
5. Keywords can not be used as an Identifier.
Example: Correct identifiers: sum, _area_of_circle
Incorrect identifiers: 1number, case, total of a&b
VARIABLES
A named memory location used to store data and whose value may change during the
program execution is called as Variable.
Variable in C++ is an identifier that refers to data item stored at a particular memory
location.
Rules for naming variable:
1. Variables can consist of alphabets, digits and a special symbol i.e. ‘_’ underscore.
2. Variables should not start with digit.
3. Variables are case sensitive so the max and MAX are considered as two different
identifiers.
4. A variable should not contain special symbols, comma or blank space.
5. Keywords can not be used as Variable Name.
Variable Declaration:
The variable must be declared before they are used in the program. Once the variable is
declared, compilers obtains the name of variable and the compiler is notified about the
data type of variable being declared and helps in allocation of memory.
Syntax:
data_type variable_name;
Example:
int a;
Variable Initialization
Assigning or storing the value to the variable is called as Variable Initialization. Variables
declared can be initialized using assignment operator (=).
Syntax:
data_type variable_name = value;
Example:
int x =50;
Dynamic Initialization
In this method, the variable is assigned a value at the run-time. The value of these
variables can be altered every time the program runs.
Example:
int a;
cin>>a;
CONSTANTS
Constants refer to fixed values that do not change during execution of a program.
Like c, c++ supports several literal constants.
They include integers, characters, floating point numbers and strings.
There are two ways in which constants can be defined:
a) Using # define preprocessor
This directive is used to declare an alias name for existing variable or any value.
We can use this to declare a constant as shown below:
Syntax: #define constant_name value
eg: #define PI 3.14
b) Using const keyword
syntax: const datatype constant_name = value;
eg: const int x = 10;
Program 1:- (Using #define preprocessor directive)
#include<iostream.h>
#include<conio.h>
#define PI 3.14
void main()
{
int radius;
float area;
clrscr();
cout<<"Enter radius\n";
cin>>radius;
area= PI * radius * radius;
cout<<"Area of Circle is "<<area;
getch();
}
Program 2:- (Using keyword const)
#include<iostream.h>
#include<conio.h>
void main()
{
int radius;
float area;
clrscr();
const float PI = 3.14;
cout<<"Enter radius\n";
cin>>radius;
area= PI * radius * radius;
cout<<"Area of Circle is "<<area;
getch();
}
DATA TYPES
Data types specify the type of data that a variable can store.
Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared.
BUILT-IN DATA TYPES / BASIC DATA TYPES
Built in data types are atomic data types which is not composed of other data types.
C++ basic data types are integer, float, character and boolean.
Data Size Description
Type
int 4 bytes Stores whole numbers, without decimals Ex. 19
float 4 bytes Stores fractional numbers, containing one or more decimals.
Sufficient for storing 7 decimal digits Ex: 19.3125876
double 8 bytes Stores fractional numbers, containing one or more decimals.
Sufficient for storing 15 decimal digits Ex: 19.32365789345
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number
The void data type is used for specifying an empty parameter list to a function and return
type for a function. When it is used as a return type for a function, it indicates that a function
does not return any value
TYPE CASTING
Type conversion means converting one type of data to another compatible type such that it
doesn't lose its meaning.
There are two types of type conversion in C++.
1. Implicit Conversion (Automatic Conversion)
2. Explicit Conversion (also known as Type Casting)
1. Implicit Type Conversion
The type conversion that is done automatically by the compiler is known as implicit
type conversion. This type of conversion is also known as automatic conversion.
It happens automatically when:
Operations are performed on values of different data types.
Assigning a value of one data type to a variable of another data type.
Example 1:
#include <iostream.h>
int main()
{
int i = 10;
char c = 'a';
// c implicitly converted to int. ASCII
// value of 'a' is 97
i = i + c;
// i is implicitly converted to float
float f = i + 1.5;
cout << "i = " << i << endl
<< "c = " << c << endl
<< "f = " << f;
return 0;
}
Example 2: Conversion From float to int
#include <iostream.h>
#include<conio.h>
void main()
{
int num1;
float num2 = 9.99;
num1 = num2;
cout << "num1 = " << num1 << endl; // 9
cout << "num2 = " << num2 << endl; // 9.99
getch();
}
In the program, we have assigned a float data to an int variable.
num1 = num2;
Here, the float value is automatically converted to int by the compiler.
Note: Since int cannot have a decimal part, the digits after the decimal point are truncated in the
above example.
When data of a larger type is converted to data of a smaller type, it may lead to data loss.
2. Explicit conversion (type casting) :-
When the user manually changes data from one type to another, this is known as explicit
conversion. This type of conversion is also known as type casting.
Syntax:
(data_type)expression;
#include <iostream>
using namespace std;
int main ()
{
int a=21;
int b = 5;
float res;
res = (float) a/ b;
cout << " Result : " << res << endl;
return 0;
}
Output:
Result : 4.2
In the above program, we take two integer variables, a and b, whose values are 21 and 5. And
then, divide a by b (21/5).
Here we declare a float type variable res that stores the results of a/b without losing any data
using the cast operator in the explicit type cast method.
STRUCTURE
C++ Structure is a collection of different data types.
Syntax:-
struct structure_name
{
// member declarations.
}
In the above declaration, a structure is declared by preceding the struct keyword followed by the
structure name. Inside the curly braces, we can declare the member variables of different types.
Example:
struct Student
{
char name[20];
int id;
int age;
}
In the above case, Student is a structure contains three variables name, id, and age. When the
structure is declared, no memory is allocated. When the variable of a structure is created, then
the memory is allocated.
How to create the instance of Structure?
Student s;
Here, s is a structure variable of type Student.
When the structure variable is created, the memory will be allocated.
How to access the members of Structure:
The members of the structure can be accessed by simply using the instance of the structure
followed by the dot (.) operator and then the member of the structure.
For example:
s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using the dot(.)
operator and assigns the value 4 to the id field.
Q] Write a C++ program to declare a structure employee with members as empid and empname.
Accept and display data for one employee using structure variable. [W -18] [3M]
#include <iostream.h>
#include<conio.h>
struct employee
{
int empid;
char empname[10];
};
void main()
{
employee e;
clrscr();
cout<<"\nEnter employee id and Employee Name ";
cin>>e.empid>>e.empname;
cout<<"\nThe Employee Id is "<<e.empid;
cout<<"\nThe Employee Name is "<<e.empname;
getch();
}
Example :-
#include <iostream>
using namespace std;
struct Student
{
char name[20];
int roll;
int marks;
};
int main()
{
Student s;
cout<<"Enter Name, Roll and Marks of Student ";
cin>>s.name;
cin>>s.roll;
cin>>s.marks;
cout<<"\n Name is "<<s.name;
cout<<"\n Roll Number is "<<s.roll;
cout<<"\n Marks is "<<s.marks;
return 0;
}
STRUCTURE OF C++ PROGRAM
Q] Explain the Structure of C++ Program? [4 M]
INCLUDE HEADER FILES
DECLARE CLASS
DEFINE MEMBER FUNCTIONS
DEFINE MAIN FUNCTION
Description:-
1. Include header files
In this section a programmer includes all header files which are required to execute
given program (iostrem.h & conio.h). The most important file is iostream.h header file.
This file defines most of the C++ statements like cout and cin. Without this file one
cannot load C++ program.
2. Declare Class
In this section a programmer declares all classes which are required for given
program. The programmer uses general syntax of creating class.
3. Define Member Functions
In this section a programmer design body of member functions of a class.
The programmer can have inside declaration of a function or outside declaration of a
function.
4. Define Main Functions
In this section, the programmer creates objects and calls various functions written
within classes.
CLASS AND OBJECT
INTRODUCTION, SPECIFYING A CLASS
A class is a collection of objects of similar type.
It is a way to bind data and its associated functions together.
It is a blueproint to create Objects.
Class specification has two parts:
1. class declaration
2. class function definition
General form of class declaration:
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
The keyword class is used to declare a class.
The body of class is enclosed within bracket and terminated by a semicolon.
Body of class contains declaration of variables and functions.
The variables are known as data members and the functions are known as member
functions.
These variables and functions are collectively called as class members.
Example:
class student
{
private:
int roll;
char name [30];
public:
void getdata ( ) ;
void putdata ( );
};
ACCESS SPECIFIERS
The class members are usually grouped under two sections namely public and private, which are
known as access specifiers or visibility modes.
1. private:
The class members that are declared as private can only be accessed from within the
class.
Only member functions can access the private data members and private member
functions.
2. public:
The class members that are declared as public can be accessed from outside the class
also.
That means public data members and public member functions can be accessed from
outside the class.
If both the labels are missing, then by default, the members of class are private.
DEFINING MEMBER FUNCTIONS
Member functions can be defined in two ways:
1. Inside class definition
In this method, function declaration and definition is written inside the class.
General syntax:
class class_name
{
…
…
public:
return_type function_name(arguments)
{
function body
}
};
Example:
class Student
{
char name[20];
int roll;
public:
void getdata( )
{
cout<<”Enter name and roll”;
cin>>name>>roll;
}
void putdata()
{
cout<<”Name is ”<<name;
cout<<”Roll Number is ”<<roll;
}
};
void main( )
{
Student S1;
S1.gedata();
S1.putdata();
getch();
}
When a function is defined inside the class, it is called as Inline function.
Here function getdata() and pudata() are inline function.
2. Outside class definition
Q] How function is defined outside of class, write general syntax and example of same.
Member functions that are declared inside class have to be defined separately outside class.
Their definitions are as simple as normal function definition.
They should have function header & body.
Member function has membership “identity label” in header.
General syntax:
class class_name
{
…
…
public:
return_type function_name(arguments);
};
return-type class-name:: function-name(arguments)
{
function body
}
Membership label class-name:: tell complier that function-name belongs to class class-name.
That is the scope of function function_name is restricted to class-name specified in header line.
Example:
class Student
{
char name[20];
int roll;
public:
void getdata( );
void putdata();
};
void Student :: getdata( )
{
cout<<”Enter name and roll”;
cin>>name>>roll;
}
void Student :: putdata()
{
cout<<”Name is ”<<name;
cout<<”Roll Number is ”<<roll;
}
void main( )
{
Student S1;
S1.gedata();
S1.putdata();
getch();
}
In above example, function getdata( ) and putdata() are declared in class demo and defined
outside the class.
CREATING OBJECTS
Q] What are objects? How are they created?
Once a class has been declared, we can create variables of class by using the class name.
eg.
item x; //memory for x is created
In C++, class variables are known as objects. Hence x is called object of type item.
We can also declare more than one object in one statement.
eg.
item x,y,z;
Class specification only provides template and does not allocate any memory space for objects.
The necessary memory is allocated during declaration of object.
Objects can also be created when a class is defined by placing their names immediately after the
closing braces.
eg.
class item
{
.…
…..
} x, y, z;
This would create objects x,y and z of type item.
ACCESSING CLASS MEMBERS
The private data of a class can be accessed only through the member function of that class.
The format for calling a member function is :
object_name.function_name(actual arguments);
eg.
S1.getdata();
Example 1:
#include<iostream.h>
#include<conio.h>
class Student
{
char name[20];
int roll;
public:
void getdata()
{
cout<<"Enter Name and roll Number \n";
cin>>name>>roll;
}
void putdata()
{
cout<<"\n Name is "<<name;
cout<<"\n Roll Number is "<<roll;
}
};
void main()
{
clrscr();
Student s1;
s1.getdata();
s1.putdata();
getch();
}
Example 2:- WAP to accept name, author and price of two books and display the details.
#include<iostream.h>
#include<conio.h>
class Book
{
char name[20];
char author[20];
float price;
public:
void accept()
{
cout<<"\nEnter Name,Author and Price\n";
cin>>name>>author>>price;
}
void display()
{
cout<<"\n Name is "<<name;
cout<<"\n Author is "<<author;
cout<<"\n Price is "<<price;
}
};
void main()
{
clrscr();
Book b1,b2;
cout<<"\n Enter Details of First Book" ;
b1.accept();
cout<<"\n Enter Details of Second Book";
b2.accept();
cout<<"\n Book 1 Details are : \n";
b1.display();
cout<<"\n Book 2 Details are : \n";
b2.display();
getch();
}
MEMORY ALLOCATION FOR OBJECTS
1. The memory space for object
The memory space for object is allocated when they are declared & not when the class is
specified.
2. The memory space for member functions
Actually, the member functions are created & placed in memory space only once when they are
defined as a part of a class definition.
Since all the objects belonging to that class use the same member functions, no separate space is
allocated for member functions.
3. The memory space for member variable
When the objects are created only space for member variable is allocated separately for each
object.
Separate memory locations for the objects are essential because the member variables will hold
different data values for different objects this is shown in fig.
SCOPE RESOLUTION OPERATOR
Q] State scope resolution operator and memory management operator in C++.
(Scope resolution operator 2M, memory management operator (any one) 2M
Use 1:-
It is used to uncover a hidden variable.
Scope resolution operator allows access to the global version of a variable.
The scope resolution operator is used to refer variable of class anywhere in program.
It takes the following form:
: : variable_name
Example:
#include <iostream>
using namespace std;
// Global x
int x = 3;
int main()
{
// Local x
int x = 10;
// Printing the global
// variable x
cout << ::x;
return 0;
}
User 2:-
Scope resolution operator is also used in classes to identify the class to which a member function
belongs. Scope resolution operator is used to define function outside of class.
return_type class_name :: function_name( )
Function body
}
MEMORY MANAGEMENT OPERATOR
Q] What are the Memory Management Operators used in C++?
There are two types of memory management operators in C++:
1. new
2. delete
These two memory management operators are used for allocating and freeing memory
block in efficient and convenient ways.
1. new operator
The new operator in C++ is used for dynamic storage allocation.
This operator can be used to create object of any type.
The general syntax of new operator in C++ is as follows:
pointer variable = new datatype;
For example:
int *p = new int;
2. delete operator
The delete operator in C++ is used for releasing memory space when the object is no
longer needed.
Once a new operator is used, it is efficient to use the corresponding delete operator for
release of memory.
General syntax of delete operator in C++:
delete pointer_variable;
For example:
delete p;
‘cin’ and ‘cout’
Q] Describe syntax of ‘cin’ and ‘cout’ with example.
(cin syntax - 1 Mark, example - 1 Mark; cout syntax - 1 Mark, example - 1 Mark)
1. cin = cin statement is use to accept input from user.
Syntax:-
cin>>variable_name ;
Example:
cin>>i;
2. cout = cout statement is use to display output processed by computer or to display simple
messages to user.
Syntax:-
cout<<variable_name;
cout<<”Message”;
Example:
cout<<”Hello world”;
cout<<x;