0% found this document useful (0 votes)
343 views

Principles of Object-Oriented Programming PDF

The document discusses the principles of object-oriented programming (OOP). It describes the four key principles of OOP - encapsulation, abstraction, inheritance, and polymorphism. It also discusses the basic concepts of OOP including objects, classes, and how OOP provides benefits like modularity, code reuse, and maintainability. Popular object-oriented programming languages are also listed.

Uploaded by

Mahh Angle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
343 views

Principles of Object-Oriented Programming PDF

The document discusses the principles of object-oriented programming (OOP). It describes the four key principles of OOP - encapsulation, abstraction, inheritance, and polymorphism. It also discusses the basic concepts of OOP including objects, classes, and how OOP provides benefits like modularity, code reuse, and maintainability. Popular object-oriented programming languages are also listed.

Uploaded by

Mahh Angle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

C++

Principles of Object-Oriented Programming


Unit-1

DIPAK KUMAR SAHOO


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

Object-Oriented Programming (OOP) Paradigm


Object-Oriented Programming (OOP) is a programming paradigm that focuses
on the use of objects, which are instances of classes, to represent data and
behaviour. OOP is based on four key principles: encapsulation, abstraction,
inheritance, and polymorphism.
Encapsulation is the process of bundling data and methods that operate on that
data within a single unit called a class. Encapsulation allows the data to be hidden
from outside the class, and only the methods can access and modify it. This helps
to ensure data integrity and security.
Abstraction is the process of hiding implementation details while showing only
the necessary information to the user. Abstraction allows developers to create
abstract classes, which define the properties and methods that a subclass must
implement without providing any implementation details. This promotes code
reuse and simplifies code maintenance.
Inheritance is the process by which one class acquires the properties and
behaviours of another class. It allows for the creation of new classes based on
existing classes, and it promotes code reuse. Inheritance enables the creation of
hierarchies of related classes, where subclasses inherit properties and methods
from their parent class.
Polymorphism is the ability of objects to take on many forms. Polymorphism
enables multiple objects to respond to the same message or method call in
different ways. Polymorphism is achieved through method overriding, where a
subclass provides a different implementation of a method defined in its parent
class, and method overloading, where a class provides multiple methods with the
same name but different parameters.
OOP provides several advantages over other programming paradigms, including
modularity, code reuse, and maintainability. By using objects to represent data
and behaviour, OOP allows for the creation of large, complex systems that are
easier to develop and maintain over time.

Basic Concepts of OOP


The basic concepts of Object-Oriented Programming (OOP) are:
➢ Objects: Objects are instances of classes that represent real-world entities
or concepts. They have data and behaviour, which are defined by their
class.

Dipak Kumar Sahoo 1


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Classes: Classes are blueprints or templates that define the data and
behaviour of objects. They encapsulate data and methods that operate on
that data.
➢ Encapsulation: Encapsulation is the concept of hiding the internal details
of an object from the outside world. It allows for data to be protected and
accessed only through methods defined in the class.
➢ Inheritance: Inheritance is the process by which one class acquires the
properties and methods of another class. It allows for code reuse and the
creation of hierarchies of related classes.
➢ Polymorphism: Polymorphism is the concept of using a single interface
to represent different types of objects. It allows for the creation of more
flexible and reusable code.
➢ Abstraction: Abstraction is the concept of hiding the complexity of an
object and only showing the necessary details to the user. It allows for the
creation of simpler and more modular code.
By using these basic concepts, developers can create modular, reusable, and
maintainable code. OOP allows for the creation of large, complex systems that
are easier to develop and maintain over time.

Benefits of OOP
There are several benefits of using Object-Oriented Programming (OOP):
➢ Modularity: OOP allows for the creation of modular code, where each
module or class encapsulates its own data and behaviour. This makes the
code easier to understand, debug, and maintain.
➢ Code Reuse: OOP allows for the reuse of existing code through
inheritance and polymorphism. Developers can create new classes based
on existing classes, which saves time and reduces the amount of code that
needs to be written.
➢ Flexibility: OOP allows for the creation of flexible and extensible code.
Developers can easily modify existing classes or create new ones to add
new features or functionality.
➢ Security: Encapsulation in OOP provides data security by preventing
outside access to sensitive data. Only the methods defined in the class can
access and modify the data.
➢ Easier Maintenance: OOP makes it easier to maintain large software
systems by breaking them down into smaller, more manageable modules.
Changes can be made to individual modules without affecting the rest of
the system.

Dipak Kumar Sahoo 2


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Better Organization: OOP allows developers to organize code into


logical, easily understandable units. This makes it easier to understand how
the code works and to find and fix bugs.
➢ Improved Productivity: OOP can improve productivity by reducing the
amount of time and effort needed to develop and maintain code. Code
reuse, modular design, and better organization all contribute to faster
development and easier maintenance.
OOP provides a powerful set of tools for developers to create high-quality,
maintainable code that can be easily modified and extended over time.

Characteristics of OOPS
Object-Oriented Programming (OOP) has several characteristics that distinguish
it from other programming paradigms. These characteristics include:
➢ Encapsulation: Encapsulation is the process of bundling data and methods
that operate on that data within a single unit called a class. Encapsulation
allows the data to be hidden from outside the class, and only the methods
can access and modify it. This helps to ensure data integrity and security.
➢ Abstraction: Abstraction is the process of hiding implementation details
while showing only the necessary information to the user. Abstraction
allows developers to create abstract classes, which define the properties
and methods that a subclass must implement without providing any
implementation details. This promotes code reuse and simplifies code
maintenance.
➢ Inheritance: Inheritance is the process by which one class acquires the
properties and behaviours of another class. It allows for the creation of new
classes based on existing classes, and it promotes code reuse. Inheritance
enables the creation of hierarchies of related classes, where subclasses
inherit properties and methods from their parent class.
➢ Polymorphism: Polymorphism is the ability of objects to take on many
forms. Polymorphism enables multiple objects to respond to the same
message or method call in different ways. Polymorphism is achieved
through method overriding, where a subclass provides a different
implementation of a method defined in its parent class, and method
overloading, where a class provides multiple methods with the same name
but different parameters.
➢ Classes and Objects: OOP is centred around the use of classes and objects.
Classes are blueprints or templates that define the data and behaviour of
objects, while objects are instances of classes that represent real-world
entities or concepts.

Dipak Kumar Sahoo 3


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Dynamic Binding: Dynamic binding allows the selection of a method to


call at runtime rather than at compile time. This makes it easier to create
flexible and extensible code.
➢ Message Passing: OOP uses message passing to communicate between
objects. An object sends a message to another object, which then performs
the requested operation and returns a result.
These characteristics of OOP provide a powerful set of tools for developers to
create modular, reusable, and maintainable code. By using OOP principles,
developers can create large, complex systems that are easier to develop and
maintain over time.

Object Oriented Languages


Object-Oriented Programming (OOP) is a programming paradigm that is
supported by many programming languages. Some popular Object-Oriented
Programming languages include:
➢ Java: Java is a widely-used, general-purpose programming language that
is designed to be platform-independent. Java is known for its robustness,
security, and ease of use, and it is widely used for developing enterprise
applications, web applications, and mobile apps.
➢ Python: Python is a high-level, interpreted programming language that is
known for its simplicity, readability, and ease of use. Python is widely used
for scientific computing, data analysis, web development, and artificial
intelligence.
➢ C++: C++ is a general-purpose programming language that is designed to
be efficient and fast. C++ is widely used for developing operating systems,
video games, and high-performance applications.
➢ C#: C# (pronounced "C sharp") is a modern, multi-paradigm programming
language that is designed for building Windows applications, web
applications, and mobile apps. C# is similar to Java in many ways, and it
is known for its simplicity and ease of use.
➢ Ruby: Ruby is a dynamic, interpreted programming language that is
designed to be easy to use and read. Ruby is known for its simplicity,
expressiveness, and flexibility, and it is widely used for web development,
scripting, and automation.
➢ PHP: PHP is a server-side scripting language that is widely used for
developing dynamic web applications. PHP is known for its simplicity,
ease of use, and scalability, and it is widely used by web developers around
the world.

Dipak Kumar Sahoo 4


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

There are many Object-Oriented Programming languages to choose from, and


each language has its own unique features and strengths. The choice of language
depends on the specific needs of the project, the development team's expertise,
and other factors.

Applications of OOP
Object-Oriented Programming (OOP) is a powerful programming paradigm that
can be applied to many different areas of software development. Some common
applications of OOP include:
➢ Web Development: OOP is widely used in web development to create
dynamic, interactive web applications. OOP concepts such as
encapsulation, inheritance, and polymorphism can be used to create
reusable and maintainable code.
➢ Game Development: OOP is widely used in game development to create
complex, interactive games. OOP concepts such as classes, objects, and
inheritance can be used to create game objects, game logic, and game
mechanics.
➢ Mobile Development: OOP is widely used in mobile development to
create mobile apps for iOS and Android devices. OOP concepts such as
classes, objects, and inheritance can be used to create reusable code that
can be shared across different mobile platforms.
➢ Artificial Intelligence: OOP is widely used in artificial intelligence to
create intelligent agents and machine learning algorithms. OOP concepts
such as classes, objects, and inheritance can be used to create complex
neural networks and decision-making systems.
➢ Enterprise Software Development: OOP is widely used in enterprise
software development to create complex, scalable systems that can be used
by large organizations. OOP concepts such as encapsulation, inheritance,
and polymorphism can be used to create reusable and maintainable code
that can be easily extended and customized.
OOP is a powerful programming paradigm that can be applied to many different
areas of software development. By using OOP principles, developers can create
modular, reusable, and maintainable code that is easier to develop and maintain
over time.

Dipak Kumar Sahoo 5


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

Introduction to C++
C++ is a general-purpose programming language that was created in the 1980s as
an extension of the C programming language. It is an object-oriented
programming (OOP) language that is widely used for developing high-
performance applications, including operating systems, video games, and
scientific simulations.
One of the main features of C++ is its support for object-oriented programming.
C++ allows developers to define classes, which are user-defined types that
encapsulate data and functionality. Classes can be used to create objects, which
are instances of a class, and these objects can be used to perform operations and
manipulate data.
C++ is also known for its high performance and efficiency. C++ programs can be
compiled to native machine code, which means that they can run much faster than
interpreted languages like Python or JavaScript. C++ also provides low-level
control over hardware resources, which makes it ideal for developing system-
level software.
In addition to its support for OOP and high performance, C++ also provides many
other features that make it a versatile and powerful programming language. Some
of these features include support for templates, which allow developers to write
generic code that can be used with different data types, and support for operator
overloading, which allows developers to define custom operators for their classes.
C++ is a powerful and flexible programming language that is widely used for
developing high-performance applications. Its support for OOP and low-level
control makes it an ideal choice for developing operating systems and other
system-level software, while its versatility and performance make it a popular
choice for developing video games and scientific simulations.

Difference between C & C++


C and C++ are both high-level programming languages, but they have some
important differences. Here are some key differences between C and C++:
➢ Object-Oriented Programming (OOP) Support: C++ supports OOP,
whereas C does not. C++ allows developers to define classes, objects, and
inheritance, which makes it easier to write modular and reusable code.
➢ Abstraction: C++ provides more advanced features for abstraction, such
as templates, virtual functions, and operator overloading. C does not

Dipak Kumar Sahoo 6


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

support these features, which can make it more difficult to write reusable
code.
➢ Compatibility: C++ is largely compatible with C code, which means that
C code can be used in C++ programs. However, the reverse is not true - C
does not support many of the features of C++, which means that C++ code
cannot be used in C programs without modification.
➢ Standard Libraries: C++ has a larger standard library than C, which
provides additional functionality and makes it easier to write programs
without relying on external libraries.
➢ Pointers: Both C and C++ support pointers, but C++ provides additional
features, such as references and smart pointers, which make it easier to
manage memory and avoid common programming errors.
➢ Execution Speed: C and C++ are both compiled languages, but C++ code
may run slightly slower than equivalent C code due to its additional
features and complexity.
Overall, while C and C++ share many similarities, C++ provides additional
features that make it easier to write modular and reusable code, while C is a
simpler language that is often used for systems programming or low-level
programming tasks.

Structure of C++ Program


The basic structure of a C++ program is composed of several parts, which are:
➢ Preprocessor Directives: This is the first part of a C++ program, which
includes a set of instructions to the compiler about how to process the
program. The most commonly used preprocessor directive is "#include",
which is used to include header files in the program.
➢ Namespace Declaration: A namespace is a mechanism for grouping
related classes, functions, and variables, and it is used to avoid naming
conflicts. The namespace declaration is used to define a namespace in
which the program is defined.
➢ Main Function: The main function is the starting point of the program,
and it is where the program execution begins. The main function must be
defined in every C++ program and it returns an integer value, which
indicates whether the program executed successfully or not.
➢ Variables Declaration: In C++, variables are declared before they are
used. A variable declaration specifies the data type of the variable and its
name. Variables can be declared at any point in the program, but it is a
good practice to declare them at the beginning of the program.

Dipak Kumar Sahoo 7


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Statements and Expressions: Statements are the building blocks of a C++


program. They are composed of expressions, which are combinations of
operators and operands that produce a result. Statements can be used to
control the flow of a program, such as loops and conditional statements.
➢ Functions: Functions are a set of statements that perform a specific task.
Functions can be called from anywhere in the program, and they can return
a value to the calling function or simply perform a task.
➢ Comments: Comments are used to explain the purpose of the program or
specific parts of the program. Comments are not executed by the compiler
and are ignored during program execution.
Here is an example of a basic C++ program structure:
#include <iostream>
using namespace std;
int main() {
// Variable declaration
int num1, num2, sum;
// Statements
cout << "Enter two numbers: ";
cin >> num1 >> num2;
sum = num1 + num2;
// Output the result
cout << "Sum of " << num1 << " and " << num2 << " is " << sum;
return 0;
}
In this example, we have included the "iostream" header file, declared the "std"
namespace, defined the main function, declared variables, used statements and
expressions, and used comments to explain the purpose of the program.

Tokens
In C++, tokens are the basic building blocks of the language, which are used to
create statements and expressions. There are several types of tokens in C++,
including:

Dipak Kumar Sahoo 8


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Keywords: Keywords are reserved words that have a specific meaning in


the language and cannot be used as identifiers.
auto bool break case catch char
class const constexpr continue default delete
do double else enum explicit export
extern false float for friend goto
if inline int long mutable
namespace
new noexcept nullptr operator private protected
public register reinterpret_cast return short
signed sizeof static static_assert static_cast struct
switch template this thread_local throw true
try typedef typeid typename union unsigned
using virtual void volatile wchar_t while
Examples of C++ keywords include "if", "else", "for", "while", "class",
and "return".
➢ Identifiers: Identifiers are used to give names to variables, functions,
classes, and other program elements. In C++, identifiers must start with a
letter or underscore, and can contain letters, numbers, and underscores.
Examples of C++ identifiers include variable names like "count" or "total",
function names like "calculateTotal" or "printResults", and class names
like "Customer" or "Employee".
➢ Literals: Literals are fixed values that are directly written into the code,
such as integers, floating-point numbers, characters, and strings.
Examples of C++ literals include integers like 42, floating-point numbers
like 3.14, characters like 'A', and strings like "Hello, world!".
➢ Operators: Operators are symbols or keywords used to perform operations
on data, such as arithmetic or logical operations.
Examples of C++ operators include arithmetic operators like +, -, *, and /,
comparison operators like == and !=, and logical operators like && and ||.
➢ Punctuation Symbols: Punctuation symbols are used to separate and
structure the code, such as parentheses, commas, semicolons, and braces.
Examples of C++ punctuation symbols include (), {}, ;, and ,.
C++ programs are parsed by the compiler, which analyzes the code by breaking
it down into tokens and using a grammar to determine how they fit together.
Understanding the different types of tokens in C++ is important for writing and
debugging C++ code.

Data Types

Dipak Kumar Sahoo 9


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

In C++, data types are used to define the type of data that a variable or expression
can hold. C++ provides several built-in data types, which can be classified into
the following categories:
1. Fundamental Data Types: These are the basic data types that are built
into the C++ language. These are also known as primitive / built-in
datatypes. These data types represent the most basic data that can be stored
in a variable. The fundamental data types in C++ are:
➢ Integer Types: These data types are used to represent whole numbers.
They include:
❖ int: This is used to represent integer values. It typically takes up 4
bytes of memory.
❖ short: This is used to represent smaller integer values. It typically
takes up 2 bytes of memory.
❖ long: This is used to represent larger integer values. It typically takes
up 4 or 8 bytes of memory, depending on the compiler and platform.
❖ long int: This is used to represent very large integer values. It
typically takes up 8 bytes of memory.
➢ Floating-Point Types: These data types are used to represent real numbers
with fractional parts. They include:
❖ float: This is used to represent single-precision floating-point
values. It typically takes up 4 bytes of memory.
❖ double: This is used to represent double-precision floating-point
values. It typically takes up 8 bytes of memory.
❖ long double: This is used to represent extended-precision floating-
point values. It typically takes up 10 or 12 bytes of memory,
depending on the compiler and platform.
➢ Character Types: These data types are used to represent single characters.
They include:
❖ char: This is used to represent single characters. It typically takes up
1 byte of memory.
❖ wchar_t: This is used to represent wide characters. It typically takes
up 2 or 4 bytes of memory, depending on the compiler and platform.
❖ Boolean type: This data type is used to represent logical values,
which can be either true or false. It is typically represented using the
keywords "true" and "false".
Understanding the fundamental data types in C++ is essential for writing efficient
and effective code. By choosing the appropriate data type for a variable, you can
optimize memory usage and ensure that your program behaves correctly.

Dipak Kumar Sahoo 10


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

2. Derived Data Types: These are types that are derived from the
fundamental data types. They include:
➢ Arrays: An array is a collection of data items of the same type that are
stored in a contiguous block of memory. Array elements can be accessed
using an index that identifies the position of the element in the array. For
example, int myArray[10] defines an array of 10 integers.
➢ Pointers: A pointer is a variable that stores the memory address of another
variable. Pointers are used to manipulate data indirectly and to pass
parameters by reference. For example, int* myPtr; declares a pointer to an
integer.
➢ References: A reference is an alias for an existing variable. A reference
can be thought of as another name for the same variable. References are
used to pass parameters by reference and to create more readable code. For
example, int x = 10; int& myRef = x; declares a reference myRef to the
variable x.
➢ Structures: A structure is a collection of related data items that can be of
different types. A structure is defined using the struct keyword. For
example, struct Person {string name; int age;} defines a structure that
contains a name and age.
➢ Unions: A union is a special type of structure where all members share the
same memory space. A union is defined using the union keyword. For
example, union Data {int i; float f;}; defines a union that can hold either
an integer or a floating-point value.
Derived data types are used to create more complex data structures in C++.
Understanding these data types is essential for writing more advanced programs
that manipulate data in various ways.
3. User-Defined Data Types: These are types that are defined by the
programmer. In C++, user-defined data types are types that are created by
the programmer. They are based on the fundamental data types and can be
customized to suit specific program needs. User-defined data types
include:
➢ Classes: A class is a user-defined data type that encapsulates data and
functions that operate on that data. A class is defined using the class
keyword.
For example,
class Person
{
private: string name;
int age;

Dipak Kumar Sahoo 11


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

public:
void setName(string n)
{
name = n;
}
string getName()
{
return name;
}
void setAge(int a)
{
age = a;
}
int getAge()
{
return age;
}
};
➢ Structures: In addition to the built-in structure data type, C++ allows the
programmer to create custom structures using the struct keyword.
Structures are similar to classes, but are less flexible and less powerful.
➢ Enumerations: An enumeration is a user-defined data type that consists
of a set of named constants. Enumerations are useful for creating a set of
related values that are used throughout a program. Enumerations are
defined using the enum keyword.
For example,
enum Color {Red, Green, Blue};
➢ Typedef: The typedef keyword allows the programmer to create a new
name for an existing data type. Typedef can be used to create more
descriptive and meaningful names for data types.
For example,
typedef int StudentID;
creates a new data type called StudentID that is equivalent to the integer
data type.
User-defined data types are an important feature of C++ that allows the
programmer to create more complex and flexible programs. Classes and
structures are the most commonly used user-defined data types, as they allow the
programmer to create custom data types that can encapsulate data and functions.

Dipak Kumar Sahoo 12


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

Operators
In C++, operators are special symbols or keywords that are used to perform
operations on one or more operands. C++ provides several types of operators,
including:
➢ Arithmetic Operators: Used to perform basic mathematical operations
such as addition (+), subtraction (-), multiplication (*), division (/), and
modulus (%).
Example:
int x = 5;
int y = 2;
int sum = x + y; // Addition
int diff = x - y; // Subtraction
int product = x * y; // Multiplication
int quotient = x / y; // Division
int remainder = x % y; // Modulus
➢ Relational Operators: Used to compare two values and return a Boolean
value (true or false). Examples of relational operators include equals to (==),
not equals to (!=), greater than (>), less than (<), greater than or equal to
(>=), and less than or equal to (<=).
Example:
int a = 5;
int b = 10;
bool isEqual = (a == b); // Equality check
bool isNotEqual = (a != b); // Inequality check
bool isGreater = (a > b); // Greater than check
bool isLess = (a < b); // Less than check
bool isGreaterOrEqual = (a >= b); // Greater than or equal to check
bool isLessOrEqual = (a <= b); // Less than or equal to check
➢ Logical Operators: Used to perform logical operations such as AND (&&),
OR (||), and NOT (!). These operators are often used in conjunction with
relational operators to form more complex expressions.
Example:
bool a = true;
bool b = false;
bool result1 = (a && b); // AND operation
bool result2 = (a || b); // OR operation
bool result3 = !a; // NOT operation

Dipak Kumar Sahoo 13


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Assignment Operators: Used to assign a value to a variable. Examples of


assignment operators include the equal sign (=), plus equals (+=), minus
equals (-=), multiplication equals (*=), and division equals (/=).
Example:
int x = 5;
x += 2; // x is now 7
x -= 3; // x is now 4
x *= 2; // x is now 8
x /= 4; // x is now 2
x %= 3; // x is now 2 (2 mod 3 is 2)
➢ Increment and Decrement Operators: Used to increase or decrease the
value of a variable by one. The increment operator is denoted by the plus
plus (++) symbol, while the decrement operator is denoted by the minus
minus (--) symbol.
Example:
int x = 5;
x++; // Increment x by 1 (x is now 6)
x--; // Decrement x by 1 (x is now 5)
➢ Bitwise Operators: Used to perform operations on the binary representation
of numbers. Examples of bitwise operators include AND (&), OR (|), XOR
(^), left shift (<<), and right shift (>>).
Example:
int a = 5; // 101 in binary
int b = 3; // 011 in binary
int result1 = (a & b); // Bitwise AND operation (result is 001, or 1 in decimal)
int result2 = (a | b); // Bitwise OR operation (result is 111, or 7 in decimal)
int result3 = (a ^ b); // Bitwise XOR operation (result is 110, or 6 in decimal)
int result4 = (a << 1); // Left shift by 1 (result is 1010, or 10 in decimal)
int result5 = (b >> 1); // Right shift by 1 (result is 001, or 1 in decimal)
➢ Conditional Operator: Used to perform a ternary operation that evaluates
a Boolean expression and returns one of two values depending on the result.
The conditional operator is denoted by the question mark (?) and the colon
(:).
➢ Member Access Operators: Used to access the members of an object or
structure. The dot operator (.) is used to access the public members of an
object, while the arrow operator (->) is used to access the public members
of a pointer to an object.
These are some of the most common operators in C++, but there are many more.
Understanding operators is an important part of learning to program in C++.

Dipak Kumar Sahoo 14


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

C++ Statements
In C++, statements are the individual instructions that make up a program. Each
statement performs a specific action, such as assigning a value to a variable,
printing output to the console, or controlling the flow of the program.
Here are some common types of statements in C++:
➢ Expression Statement: An expression statement is a statement that
evaluates an expression and discards the result. For example:
x + y;
➢ Declaration Statement: A declaration statement declares a variable or a
function. For example:
int x;
void myFunction();
➢ Control Statement: A control statement is used to control the flow of a
program. Examples of control statements include if/else statements, switch
statements, loops (for, while, do-while), and jump statements (break,
continue, return, goto).
➢ Compound Statement: A compound statement is a statement that
contains a block of statements enclosed in braces {}. For example:
{
int x = 5;
int y = 10;
int sum = x + y;
cout << "The sum of " << x << " and " << y << " is " << sum;
}
➢ Expression Statement: An expression statement is a statement that
evaluates an expression and discards the result. For example:
x + y;
➢ Null Statement: A null statement is an empty statement that does nothing.
It is represented by a semicolon. For example:
;

Dipak Kumar Sahoo 15


PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

➢ Try-catch Statement: A try-catch statement is used to handle exceptions


that may occur during program execution. The try block contains the code
that may throw an exception, and the catch block contains the code that
handles the exception. For example:
try {
// Code that may throw an exception
}
catch (exception ex) {
// Code that handles the exception
}
These are just a few examples of the types of statements that can be used in C++.
The different types of statements can be combined to create complex programs
that perform a wide range of tasks.

Dipak Kumar Sahoo 16

You might also like