You are on page 1of 51

Object Oriented Programming Concepts

Procedural Programming

• Procedural programming is a programming paradigm that follows a linear, step-


by-step approach to problem-solving.
• It is based on the concept of procedures or routines, which are sequences of
instructions that perform a specific task.
Key Concepts

• Procedures/Functions: These are blocks of code that perform a specific task. They can take input,
process it, and produce output.
• Global Variables: Data is often shared through global variables, which can be accessed by any
part of the program.
• Top-Down Approach: The program is designed and implemented in a top-down fashion, breaking
down the problem into smaller, manageable
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
int num1 = 5,
num2 = 10;
int result = add(num1, num2);
printf("Sum: %d\n", result);
return 0;
Problems in Procedural Programming Approach
Global Data:
• In procedural programming, global variables are often used to share data between procedures.
• This can lead to issues such as unintended side effects, data corruption, and difficulties in tracking changes to variables.
Lack of Encapsulation:
• Procedural programming lacks strong encapsulation mechanisms.
• Data and functions are not bundled together into a single unit, making it harder to control access and modification of
data.
Code Duplication:
• Without the concept of reusable objects, procedural code tends to have more redundancy.
• Code duplication can make maintenance difficult, as changes may need to be made in multiple places.
Limited Code Reusability:
• Procedural programming typically does not offer as much code reusability as object-oriented programming.
• Functions are reused, but the encapsulation and modularity provided by classes in OOP make it easier to reuse and extend
code.
Difficulty in Managing Complexity:
• As programs grow in size and complexity, managing and understanding the flow of control becomes challenging in
procedural programming.
• Large procedural codebases may lack clear organization and structure.

Poor Support for Abstraction:


• Procedural programming is often less adept at handling abstraction.
• While functions allow for some level of abstraction, they may not provide the same level of clarity and abstraction as
classes and objects in OOP.
Limited Support for Hierarchical Relationships:
• In procedural programming, managing hierarchical relationships between entities can be cumbersome.
• OOP's concept of inheritance provides a more natural way to model and manage such relationships.
Difficulty in Maintenance and Modification:
• Making changes to a procedural codebase, especially in a large project, can be challenging.
• The lack of encapsulation and clear boundaries may result in unintended consequences when modifications are made.
Less Natural Modeling of Real-World Entities:
• Procedural programming may not provide as natural a way to model real-world entities and their interactions as object-
oriented programming.
• OOP allows for more intuitive representation of entities with properties and behaviors
Limited Support for Polymorphism:
• Polymorphism, a key concept in OOP, is not as naturally supported in procedural programming.
• This can limit the flexibility and extensibility of the code.
Object-Oriented Programming (OOP)
Object-oriented programming aims to implement real-world entities in programming.

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.
Basic concepts that act as the building blocks of OOPs :

Class


Objects


Encapsulation


Abstraction


Polymorphism


Inheritance


Dynamic Binding


Message Passing
Characteristics of OOP

Class :

Building block of C++ that leads to Object-Oriented programming is a Class.

A Class is a user-defined data type that has data members and member functions.

Data members are the data variables and member functions are the functions used to
manipulate these variables

Data members and member functions define the properties and behavior of the objects in a
Class.

Class in C++ is a blueprint representing a group of objects which shares some common
properties and behaviors.

Example : Class of Cars. There may be many cars with different names and brands but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, etc.

Car is the class, and wheels, speed limits, and mileage are their properties.

Object

An Object is an identifiable entity with some
characteristics and behavior.

An Object is an instance of a Class.

When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created)
memory is allocated.

When a program is executed the objects interact by
sending messages to one another.

Each object contains data and code to manipulate
the data.

Objects can interact without having to know details
of each other’s data or code

It is sufficient to know the type of message accepted
and the type of response returned by the objects
class person
{
char name[20];
int id;
public:
void getdetails( );
};

person p ; // p is an object

Encapsulation :

Encapsulation is defined as wrapping up data and information under a single unit.

Encapsulation is defined as binding together the data and the functions that manipulate them.


Encapsulation also leads to data abstraction or data hiding.

Using encapsulation also hides the data.

Example: the data of any of the departments like sales, finance, or accounts are hidden from
any other departments
Abstraction:
Data abstraction is one of the most essential and important features of object-oriented programming in C++.
Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside world, hiding the background
details or implementation.
Abstraction allows programmers to focus on the essential aspects of an object and ignore irrelevant details.
It helps in creating a model that represents real-world entities in a more understandable and manageable way.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerator will increase the
speed of the car or applying brakes will stop the car but he does not know how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the implementation of an accelerator,
brakes, etc. in the car.
This is what abstraction is.

Abstraction using Classes:

Abstraction in C++ can be implemented using classes.

The class helps to group data members and member functions using available access specifiers
( private , public , protected )

A Class can decide which data member will be visible to the outside world and which is not.

Abstraction in Header files:

Abstraction in C++ can be with header files.

Consider the pow() method present in math.h header file.

Call the function pow() present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually calculating the power of
numbers.
Polymorphism

Polymorphism means having many forms

Polymorphism means the ability of a message to be displayed in more than one form.

A person at the same time can have different characteristics. A man at the same time is a
father, a husband, and an employee

Same person possesses different behavior in different situations.

An operation may exhibit different behaviors in different instances.

The behavior depends upon the types of data used in the operation.

C++ supports operator overloading and function overloading to implement Polymorphism

Two types of polymorphism - compile-time (method overloading) and runtime (method overriding).

Operator Overloading: The process of making an operator exhibit different behaviors in
different instances is known as operator overloading.

Function Overloading: Function overloading is using a single function name to perform
different types of tasks.

Example : function to add some integers . sometimes there are 2 integers, and sometimes
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

Capability of a class to derive properties and characteristics from another class is called
Inheritance.


Inheritance is one of the most important features of Object-Oriented Programming


Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.


Super Class: The class whose properties are inherited by a sub-class is called Base Class or
Superclass.


Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class.
Dynamic Binding

Code to be executed in response to the function call is decided at runtime.


C++ has virtual functions to support this.


Dynamic binding is flexible, it avoids the drawbacks of static binding which connected the function call and definition
at build time.


Dynamic binding supports polymorphism by enabling the selection of the appropriate method implementation based
on the actual type of the object at runtime.
Message Passing:

• Objects communicate with each other by sending and receiving messages.

• A message consists of a request for an action to be performed.

• Message passing facilitates interaction between objects.

• Objects interact by invoking methods on each other, leading to a more dynamic and flexible system.

.
User Defined Data Types

Data types are means to identify the type of data and associated operations of handling it.

Data types are used to declare the variable

Data types defined by the user are called the derived datatype or user-defined derived data
type

User Defined Data Types are :

Class

Structure

Union

Enumeration

Typedef
Class

Class is the building block of C++ that leads to Object-Oriented programming is a Class.

Class 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.
class Student
{
private:
char name[50];
int rollNumber;
public:
void getDetails( );
void displayDetails( );
};

student x, y;
x.getdetails( ); // x object can access members of the class
y.displaydetails ( ) ;
Structure

Structure is a user-defined data type in C/C++.

Structure creates a data type that can be used to group items of possibly different types into a
single type
struct student
{
char name[20];
int id ;
};

student x, y ;
x.name;
x.id ;
Union

Union is a user-defined data type.

In union, all members share the same memory location
union Name
{
// Declaration of data members
};
union test
{
int x, y;
};
union test t ;
t.x =2;
t.y =4 ;
Enumeration

Enumeration (or enum) is a user-defined data type in C.

It is mainly used to assign names to integral constants

Names make a program easy to read and maintain.

#include <iostream>
using namespace std;
enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };
int main( )
{ enum week day;
day = Wed;
cout << day;
return 0;
}
typedef

Used to create an alias (a new name) for an existing data type

It allows programmers to define their own names for data types

Makes the code more readable and provides a level of abstraction.

typedef is often used to create user-defined data types that simplify complex type declarations


typedef existing_data_type new_data_type;

typedef int bca;

int main()

bca x = 10;

cout<<x ;

return 0;

}
typedef struct
{
int day;
int month;
int year;
} Date;
int main( )
{
Date x = {17, 1, 2024};
cout<<"Today's date:"<<x.day<<"/"<< x.month<<"/"<< x.year;
return 0;
}
C++ Syntax

Syntax refers to the rules and regulations for writing statements in a programming language


They can also be viewed as the grammatical rules defining the structure of a programming language.
Namespace

namespace in C++ is used to provide a scope or a region where we define identifiers.


It is used to avoid name conflicts between two identifiers as only unique names can be used as identifiers


using namespace std;


where all standard library functions are defined
Keywords

Reserved words that are used for some special meaning in the C++ program


Some keywords are

int void if while for auto bool break

this static new true false case char class


C++ Comments

Purpose of the comments is to provide information about code lines.

Programmers commonly use comments to document their work

It makes a program more readable and gives an overall description of the code.

Comments are helpful in skipping the execution of some parts of the code.

Types of Comments in C++



Single-line comment

Multi-line comment
C++ Data Types
C++ supports the following data types:

Primary or Built-in or Fundamental data type

Derived data types

User-defined data types
Primitive Data Types

Data Type Meaning Size (in Bytes)


int Integer 2 or 4
float Floating-point 4
double Double Floating-point 8
char Character 1
wchar_t Wide Character 2
bool Boolean 1
void Empty 0
C++ int

 The int keyword is used to indicate integers.

 Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.

 For example ,

int salary = 85000;

C++ float and double

 float and double are used to store floating-point numbers (decimals and exponentials)

 The size of float is 4 bytes and the size of double is 8 bytes.

 Hence, double has two times the precision of float.

 For example,
float area = 64.74;
double volume = 134.64534;
C++ char

 Keyword char is used for characters

 Its size is 1 byte.

 Characters in C++ are enclosed inside single quotes ' '

 For example, char test = 'h';

C++ wchar_t

 Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead of 1.

 It is used to represent characters that require more memory to represent them than a single char.

C++ bool

 The bool data type has one of two possible values: true or false.

 Booleans are used in conditional statements and loops

 For example:
bool cond = false;
Data Type Modifiers
 Modify fundamental data types by using type modifiers.
There are 4 type modifiers in C++
 Signed
 Unsigned
 Short
 long
Data Type Size (in Meaning
Bytes)

signed int 4 used for integers (equivalent to int)

unsigned int 4 can only store positive integers

short 2 used for small integers (range -32768 to 32767)

unsigned short 2 used for small positive integers (range 0 to 65,535)

long at least 4 used for large integers (equivalent to long int)

unsigned long 4 used for large positive integers or 0 (equivalent to unsigned long int)

long long 8 used for very large integers (equivalent to long long int).
unsigned long long 8 used for very large positive integers or 0 (equivalent to unsigned long
long int)
long double 12 used for large floating-point numbers
signed char 1 used for characters (guaranteed range -127 to 127)
unsigned char 1 used for characters (range 0 to 255)

Example :
long b = 4523232;
long int c = 2345342;
long double d = 233434.56343;
short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store positive numbers or 0
C++ Variables

 Variables are containers for storing data values


 int x = 15;
 cout << x ; // cout object is used together with the << operator to display variables
 double y= 5.99; // Floating point number (with decimals)
char z = 'D'; // Character
string a = "Hello"; // String (text)
bool b = true;
 To combine both text and a variable, separate them with the << operator
int x = 35;
cout << " Value of x= " << x ;
 Add Variables Together
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
C++ Strings

 Strings are used for storing text


 string is an object of std::string class that represents sequence of characters
 String variable contains a collection of characters surrounded by double quotes
 string greeting = "BCA";
Operations on strings
 Concatenation
 Comparison
 conversion
Example :
#include <iostream>
using namespace std;
int main( )
{
string s1 = "BCA";
char ch[ ] = { '4', 't', 'h'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Example : String Compare
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char x[ ] = "BCA";
char y[50]; Output :
do What is my course? CSE
{ What is my course? BSC
What is my course? BCA
cout<<" What is my course? ";
Correct
cin>>y;
} while (strcmp (x, y) != 0);
cout<<" Correct "<<endl;
return 0;
}
Example : String Concat
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char x[25], y[25];
cout << "Enter the string 1: ";
cin.getline(x, 25);
cout << "Enter the string 2: "; Output:
cin.getline(y, 25); Enter the string 1: BCA
strcat(x, y); Enter the string 2: 4th Sem
Cout << " x = " << x << endl; x = BCA4th Sem
y = 4th Sem
cout << "y = " << y<<endl;
return 0;
}
Example : String Copy
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char x[25], y[25];
Output :
cout << "Enter the key string: "; Enter the key string: BCA
x = BCA
cin.getline(x, 25);
y = BCA
strcpy(y, x);
cout << " x = "<< x << endl;
cout << " y = "<< y<<endl;
return 0;
}
Example : String Length

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char x[ ] = "HelloBCA4thSemStudents";
char y[] = "Hello BCA 4th Sem Students";
cout << "Length of String = " << strlen(x)<<endl; Output :
Length of String = 22
cout << "Length of String = " << strlen(y)<<endl;
Length of String = 26
return 0;
}

You might also like