0% found this document useful (0 votes)
17 views24 pages

Unit 1

The document provides an overview of Object-Oriented Programming (OOP) principles, particularly focusing on C++ as an object-oriented language. It discusses key characteristics of OOP such as encapsulation, inheritance, polymorphism, and data hiding, while also comparing procedural programming with object-oriented programming. Additionally, it covers basic concepts, syntax, and structures of C++ programs, including function overloading and control structures.

Uploaded by

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

Unit 1

The document provides an overview of Object-Oriented Programming (OOP) principles, particularly focusing on C++ as an object-oriented language. It discusses key characteristics of OOP such as encapsulation, inheritance, polymorphism, and data hiding, while also comparing procedural programming with object-oriented programming. Additionally, it covers basic concepts, syntax, and structures of C++ programs, including function overloading and control structures.

Uploaded by

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

Object oriented Programming

Introduction:
Object-oriented programming – As the name suggests uses objects in programming.
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can access
this data except that function.
Characteristics of an Object Oriented Programming language

C++ is a general-purpose programming language that was developed as an enhancement


of the C language to include object-oriented paradigm. It is an imperative and
a compiled language. C++ is a middle-level language rendering it the advantage of
programming low-level (drivers, kernels) and even higher-level applications (games,
GUI, desktop apps etc.). The basic syntax and code structure of both C and C++ are the
same.
Some of the features & key-points to note about the programming language are as
follows:
• Simple: It is a simple language in the sense that programs can be broken down into
logical units and parts, has a rich library support and a variety of data-types.
• Machine Independent but Platform Dependent: A C++ executable is not platform-
independent (compiled programs on Linux won’t run on Windows), however they
are machine independent.
• Mid-level language: It is a mid-level language as we can do both systems-
programming (drivers, kernels, networking etc.) and builds large-scale user
applications (Media Players, Photoshop, Game Engines etc.)
• Rich library support: Has a rich library support (Both standard ~ built-in data
structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast
and rapid development.
• Speed of execution: C++ programs excel in execution speed. Since, it is a compiled
language, and also hugely procedural. Newer languages have extra in-built default
features such as garbage-collection, dynamic typing etc. which slow the execution of
the program overall. Since there is no additional processing overhead like this in
C++, it is blazing fast.
• Pointer and direct Memory-Access: C++ provides pointer support which aids users
to directly manipulate storage address. This helps in doing low-level programming
(where one might need to have explicit control on the storage of variables).
• Object-Oriented: One of the strongest points of the language which sets it apart
from C. Object-Oriented support helps C++ to make maintainable and extensible
programs. i.e. Large-scale applications can be built. Procedural code becomes
difficult to maintain as code-size grows.
• Compiled Language: C++ is a compiled language, contributing to its speed.
Comparison between Procedural Programming Paradigm and Object
Oriented Paradigm:
On the Object-oriented
S.NO. Procedural Programming
basis of programming

It is a programming language
that is derived from structure Object-oriented programming
programming and based upon is a computer programming
the concept of calling design philosophy or
1. Definition procedures. It follows a step-by- methodology that organizes/
step approach in order to break models software design around
down a task into a set of data or objects rather than
variables and routines via a functions and logic.
sequence of instructions.

Data hiding is possible in


object-oriented programming
2. Security It is less secure than OOPs. due to abstraction. So, it is more
secure than procedural
programming.

It follows a bottom-up
3. Approach It follows a top-down approach.
approach.

In procedural programming,
In OOP, objects can move and
Data data moves freely within the
4. communicate with each other
movement system from one function to
via member functions.
another.

It is structure/procedure-
5. Orientation It is object-oriented.
oriented.

The access modifiers in OOP are


Access There are no access modifiers in
6. named as private, public, and
modifiers procedural programming.
protected.

Procedural programming does There is a feature of inheritance


7. Inheritance not have the concept of in object-oriented
inheritance. programming.

There is no code reusability


Code It offers code reusability by
8. present in procedural
reusability using the feature of inheritance.
programming.
In OOP, there is a concept of
Overloading is not possible in
9. Overloading function overloading and
procedural programming.
operator overloading.

It gives importance to functions It gives importance to data over


10. Importance
over data. functions.

In procedural programming, In OOP, there is an appearance


11. Virtual class
there are no virtual classes. of virtual classes in inheritance.

Complex It is not appropriate for It is appropriate for complex


12.
problems complex problems. problems.

There is not any proper way for There is a possibility of data


13. Data hiding
data hiding. hiding.

In Procedural programming, a
In OOP, a program is divided
Program program is divided into small
14. into small parts that are
division programs that are referred to as
referred to as objects.
functions.

The examples of object-


Examples of Procedural
oriented programming are -
15. Examples programming include C,
.NET, C#, Python, Java, VB.NET,
Fortran, Pascal, and VB.
and C++.

Basic Concepts of Object Oriented Programming:


Object oriented programming is a type of programming which uses objects and classes
its functioning. The object oriented programming is based on real world entities like
inheritance, polymorphism, data hiding, etc. It aims at binding together data and
function work on these data sets into a single entity to restrict their usage.
Some basic concepts of object oriented programming are −

• Class
• Objects
• Encapsulation
• Data Hiding
• Abstraction
• Inheritance
• Overloading
• Polymorphism
• Abstraction

Class − A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in objects oriented programming language. It is
the basic building block of object oriented programming in C++. The members of a class
are accessed in programming language by creating an instance of the class.
Some important properties of class are −
• Class is a user-defined data-type.
• A class contains members like data members and member functions.
• Data members are variables of the class.
• Member functions are the methods that are used to manipulate data members.
• Data members define the properties of the class whereas the member functions
define the behavior of the class.
A class can have multiple objects which have properties and behaviour that in common
for all of them.
Syntax
class <class_name>
{
< data_type> < data_name>;
< return_type>< method_name>(parameters);
}

Object − an object is an instance of a class. It is an entity with characteristics and


behavior that are used in the object oriented programming. An object is the entity that is
created to allocate memory. A class when defined does not have memory chunk itself
which will be allocated as soon as objects are created.
Syntax
Class_name object_name;

Encapsulation In object oriented programming, encapsulation is the concept of


wrapping together of data and information in a single unit. A formale defination of
encapsulation would be: encapsulation is binding togather the data and related function
that can manipulate the data.
Let’s understand the topic with an easy real life example,
In our colleges, we have departments for each course like computer science, information
tech. , electronics, etc. each of these departments have their own students and subjects
that are kept track of and being taught. let's think of each department as a class that
encapsulates the data about students of that department and the subjects that are to be
taught. Also a department has some fixed rules and guidelines that are to be followed by
the students that course like timings, methods used while learning, etc. this is
encapsulation in real life, there are data and there are ways to manipulate data.
Due to the concept of encapsulation in object oriented programming another very
important concept is possible, it is data abstraction or Data Hiding. it is possible as
encapsulating hides the data at show only the information that is required to be
displayed.

Data Hiding: data hiding is an object-oriented pogramming technique of hiding


internal object details i.e. data members. Data hiding guarantees restricted data access to
class members & maintain object integrity

Data Abstraction Abstraction Data abstraction or Data Hiding is the concept of


hiding data and showing only relevant data to the final user. It is also an important part
object oriented programing.
let's take real life example to understand concept better, when we ride a bike we only
know that pressing the brake will stop the bike and rotating the throttle will accelerate
but you don't know how it works and it is also not think we should know that's why this
is done from the same as a concept data abstraction.

Polymorphism The name defines polymorphism is multiple forms. which means


polymorphism is the ability of object oriented programming to do some work using
multiple forms. The behaviour of the method is dependent on the type or the situation in
which the method is called.
Let’s take a real life example, A person can have more than one behavior depending upon
the situation. like a woman a mother, manager and a daughter And this define her
behaviour. This is from where the concept of polymorphism came from.
In c++ programming language, polymorphism is achieved using two ways. They are
operator overloading and function overloading.
Operator Overloading In operator overloading and operator can have multiple
behaviour in different instances of usage.
Function Overloading Functions with the same name that can do multiple types
based on some condition.
Example: Suppose we have to write a function to add some integers, some times there
are 2 integers, some times there are 3 integers. We can write the Addition Method with
the same name having different parameters, the concerned method will be called
according to parameters.
Inheritance it is the capability of a class to inherit or derive properties or
characteristics other class. it is very important and object oriented program as it allows
reusability i.e. using a method defined in another class by using inheritance. The class
that derives properties from other class is known as child class or subclass and the class
from which the properties are inherited is base class or parent class.
C plus plus programming language supports the following types of inheritance
• single inheritance
• multiple inheritance
• multi level inheritance
• Hierarchical inheritance
• hybrid inheritance
In C plus plus programming language write two ways using which we can accomplish
data abstraction −
• using class
• using header file

Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure
Structure of C++ program with simple C++ program:

Documentation Section :- Documentation section is generally meant include set of


comments, that is used to provide the information about the program written like name
of a program, utility of program, date of creation, date of last modification ,author name,
licensing or copyrights information and any other information that programmer wish to
put for the references.

Example:
//Program Name: First C++ Program

/*

Version: 1.0

Description: C++ program basic program structure.

Author: @noname

Date Created:21-02-2018*/
Link Preprocessor :- These preprocessor directive tell the compiler to link the
functions from system library.
Example:

#include <iostream>
Definition Preprocessor :- This the section where we define all our symbolic constant
we gonna use in our program.
Example:
#define PI 3.142
#define TRUE 1

Global Declarations :- This is the section where all the global declaration comes. All of
the variables, structures, classed and function defined or declared outside the main
function are treated as global.

Class Definition :- The classes are used to map real world entities into programming.
The Classes are the key building block of any C++ program. A C++ program may include
several class definitions. This is the section where we define all of our classes.

Main Function Definition : - This is the most vital part of each and every C++ program,
it is mandatory for C++ program to have a main() method definition. There can be only
one main() method in C++ program. The execution of a C++ program starts with the
main() method. The C++ program can not be executed without the main() method. The
main() method is responsible for the execution of all the user defined statement,
functions and library functions. The main() method further structured into – variable
declaration, function declaration and user defined executable statements.

User defined functions :- This is the section of where we put all the user defined
functions created to perform a specific task. A user defined function must be defined
before use it. User defined function can be written before or immediately after the main (
) function and called inside the main ( ) function.

Control Structures are just a way to specify flow of control in programs. Any
algorithm or program can be more clear and understood if they use self-contained
modules called as logic or control structures. It basically analyzes and chooses in which
direction a program flows based on certain parameters or conditions. There are three
basic types of logic, or flow of control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
Let us see them in detail:
1. Sequential Logic (Sequential Flow)
Sequential logic as the name suggests follows a serial or sequential flow in which the
flow depends on the series of instructions given to the computer. Unless new
instructions are given, the modules are executed in the obvious sequence. The
sequences may be given, by means of numbered steps explicitly. Also, implicitly
follows the order in which modules are written. Most of the processing, even some
complex problems, will generally follow this elementary flow pattern.

Sequential Control flow

2. Selection Logic (Conditional Flow)


Selection Logic simply involves a number of conditions or parameters which decides
one out of several written modules. The structures which use these type of logic are
known as Conditional Structures. These structures can be of three types:

Single Alternative This structure has the form:


if (condition)
{
}
Double Alternative This structure has the form:
if(condition)
{

}
else
{

Multiple Alternatives This structure has the form:


If (condition A)
{
[Module A]
}
else if (condition B)
{
[Module B]
..
}
else if (condition N)
{
[Module N]
}
else
{
}
Double Alternative Control Flow

Iteration Logic (Repetitive Flow): The Iteration logic employs a loop which involves a
repeat statement followed by a module known as the body of a loop.

The two types of these structures are:


For
This structure has the form:
for(initialization,condition checking,updation)
{
//body of the loop
}
Repeat-For Flow

While
initialization;
While(condition)
{
Body of the loop;
Updation;
}
Repeat While Flow

In this, there requires a statement that initializes the condition controlling the loop, and
there must also be a statement inside the module that will change this condition leading
to the end of the loop.

Function overloading in C++


Function overloading is a C++ programming feature that allows us to have more than
one function having same name but different parameter list, when I say parameter list, it
means the data type and sequence of the parameters, for example the parameters list of
a function myfuncn(int a, float b) is (int, float) which is different from the
function myfuncn(float a, int b) parameter list (float, int). Function overloading is a
compile time polymorphishm.
Lets take an example to understand function overloading in C++.
#include <iostream>
using namespace std;
class Addition
{
public:
int sum(int num1,int num2)
{
return num1+num2;
}
int sum(int num1,int num2, int num3)
{
return num1+num2+num3;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output:
35
191
Functions in C++ with example
A function is block of code which is used to perform a particular task, for example let’s
say you are writing a large C++ program and in that program you want to do a particular
task several number of times, like displaying value from 1 to 10, in order to do that you
have to write few lines of code and you need to repeat these lines every time you display
values. Another way of doing this is that you write these lines inside a function and call
that function every time you want to display values. This would make you code simple,
readable and reusable.

Syntax of Function
return_type function_name (parameter_list)
{
//C++ Statements
}
Let’s take a simple example to understand this concept.
A simple function example
#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/int
sum(int num1, int num2){
int num3 = num1+num2; return num3;
}

int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Output:

100
The same program can be written like this: Well, I am writing this program to let you
understand an important term regarding functions, which is function declaration. Lets
see the program first and then at the end of it we will discuss function declaration,
definition and calling of function.

#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);

//Main function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
Function Declaration: You have seen that I have written the same program in two
ways, in the first program I didn’t have any function declaration and in the second
program I have function declaration at the beginning of the program. The thing is that
when you define the function before the main() function in your program then you don’t
need to do function declaration but if you are writing your function after the main()
function like we did in the second program then you need to declare the function first,
else you will get compilation error.

syntax of function declaration:


return_type function_name(parameter_list);
Note: While providing parameter_list you can avoid the parameter names, just like I did
in the above example. I have given int sum(int,int); instead of int sum(int num1,int
num2);.

Function definition: Writing the full body of function is known as defining a function.
syntax of function definition:
return_type function_name(parameter_list) {
//Statements inside function
}
Calling function: We can call the function like this:

function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++

Types of function

We have two types of function in C++:


1) Built-in functions
2) User-defined functions

1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and define
these functions as they are already written in the C++ libraries such as iostream, cmath
etc. We can directly call them when we need.

Example: C++ built-in function example


Here we are using built-in function pow(x,y) which is x to the power y. This function is
declared in cmath header file so we have included the file in our program
using #include directive.

#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}

Output:

32
2) User-defined functions

We have already seen user-defined functions, the example we have given at the
beginning of this note is an example of user-defined function. The functions that we
declare and write in our programs are user-defined functions. Lets see another example
of user-defined functions.

User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);

int main()
{
int x, y;
cout<<"enter first number: ";
cin>> x;

cout<<"enter second number: ";


cin>>y;

cout<<"Sum of these two :"<<sum(x,y);


return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output:

enter first number: 22


enter second number: 19
Sum of these two :41

Function Prototyping In C++

Function Prototyping is the process of declaring a function for the compiler to


understand the function name, arguments, and return type.

Function Declaration
return_type function_name( param_1,param_2 ... param_n );
main() Function in C++

main() function is the entry point of any C++ program. It is the point at which
execution of program is started. When a C++ program is executed, the execution
control goes directly to the main() function. Every C++ program have a main()
function.
Void main()
{
……………………
……………………..
}

In above syntax;

• void: is a keyword in C++ language, void means nothing, whenever we use void as
a function return type then that function nothing return. here main() function no
return any value.
• In place of void we can also use int return type of main() function, at that time
main() return integer type value.
• main: is a name of function which is predefined function in C++ library.

Simple example of main()


Example

#include<iostream>
using namespace std;
void main()
{
cout<<"This is main function";
}

Output
This is main function

Inline function in C++


If make a function as inline, then the compiler replaces the function calling location with
the definition of the inline function at compile time.

Any changes made to an inline function will require the inline function to be recompiled
again because the compiler would need to replace all the code with a new code;
otherwise, it will execute the old functionality.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code?
}
Let's understand the difference between the normal function and the inline
function.

Inside the main() method, when the function fun1() is called, the control is transferred
to the definition of the called function. The addresses from where the function is called
and the definition of the function are different. This control transfer takes a lot of time
and increases the overhead.

When the inline function is encountered, then the definition of the function is copied to
it. In this case, there is no control transfer which saves a lot of time and also decreases
the overhead.

Let's understand through an example.

#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;

}
Once the compilation is done, the code would be like as shown as below:

#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}

Why do we need an inline function in C++?

The main use of the inline function in C++ is to save memory space. Whenever the
function is called, then it takes a lot of time to execute the tasks, such as moving to the
calling function. If the length of the function is small, then the substantial amount of
execution time is spent in such overheads, and sometimes time taken required for
moving to the calling function will be greater than the time taken required to execute
that function.

The solution to this problem is to use macro definitions known as macros. The
preprocessor macros are widely used in C, but the major drawback with the macros is
that these are not normal functions which means the error checking process will not be
done during the compilation.

C++ has provided one solution to this problem. In the case of function calling, the time
for calling such small functions is huge, so to overcome such a problem, a new concept
was introduced known as an inline function. When the function is encountered inside
the main() method, it is expanded with its definition thus saving time.

We cannot provide the inlining to the functions in the following circumstances:

o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.
o If a function contains a switch or go to statement

When do we require an inline function?

An inline function can be used in the following scenarios:

o An inline function can be used when the performance is required.


o It can be used over the macros.
o We can use the inline function outside the class so that we can hide the internal
implementation of the function.

Advantages of inline function


o In the inline function, we do not need to call a function, so it does not cause any
overhead.
o It also saves the overhead of the return statement from a function.
o It does not require any stack on which we can push or pop the variables as it does not
perform any function calling.
o An inline function is mainly beneficial for the embedded systems as it yields less code
than a normal function.

Disadvantages of inline function


The following are the disadvantages of an inline function:

o The variables that are created inside the inline function will consume additional registers.
If the variables increase, then the use of registers also increases, which may increase the
overhead on register variable resource utilization. It means that when the function call is
replaced with an inline function body, then the number of variables also increases,
leading to an increase in the number of registers. This causes an overhead on resource
utilization.
o If we use many inline functions, then the binary executable file also becomes large.
o The use of so many inline functions can reduce the instruction cache hit rate, reducing
the speed of instruction fetch from the cache memory to that of the primary memory.
o It also increases the compile-time overhead because whenever the changes are made
inside the inline function, then the code needs to be recompiled again to reflect the
changes; otherwise, it will execute the old functionality.
o Sometimes inline functions are not useful for many embedded systems because, in some
cases, the size of the embedded is considered more important than the speed.
o It can also cause thrashing due to the increase in the size of the binary executable file. If
the thrashing occurs in the memory, then it leads to the degradation in the performance
of the computer.

You might also like