Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing and modeling software as a collection of objects. In OOP, objects are instances of classes, which serve as blueprints or templates for defining the structure and behavior of those objects. OOP is built on several key principles and concepts, which include:
Objects: Objects are the basic building blocks of an OOP system. They represent real-world entities, and they encapsulate both data (attributes or properties) and behavior (methods or functions) that operate on that data.
Classes: Classes are the templates or blueprints from which objects are created. They define the attributes and methods that objects of the class will possess. Classes enable the concept of abstraction, allowing you to create objects with common characteristics and behaviors.
Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit, i.e., a class. This unit is called an object. Encapsulation restricts access to the internal state of an object, providing data hiding and promoting information hiding, which helps manage complexity and reduces potential issues.
Inheritance: Inheritance is a mechanism that allows a class (a child or derived class) to inherit the attributes and methods of another class (a parent or base class). This promotes code reusability and the creation of specialized classes.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the use of a single interface to represent a general class of actions. Polymorphism can take the form of method overriding (a subclass provides a specific implementation of a method defined in its superclass) or method overloading (multiple methods with the same name but different parameters).
Abstraction: Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors. It hides the unnecessary details while providing a clear and well-defined interface for interacting with objects.
Object-Oriented Programming is widely used in various programming languages like C++, Java, C#, Python, and more. It promotes code organization, modularity, and the modeling of real-world entities in a way that makes it easier to design, develop, and maintain software systems. OOP is particularly suited for large and complex projects where code readability, reusability, and maintainability are critical.
1. INTRODUCTION TO
OBJECT ORIENTED PROGRAMMING
1. Principles of OOP
2. Applications and structure of C++ program
3. Different Data types, Variables
4. Different Operators, expressions, operator overloading,
5. control structures in C++.
Ms.S.DEEPA M.E.,(Ph.d.)
Assistant Professor (SL.G)
Computer Science and Engineering
KIT-Kalaignarkarunanidhi Institute Of Technology
2. C++ Data Types
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
Data Type Size Description
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number, or ASCII values
int 2 or 4 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 6-7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits
3. Introduction to User-Defined Data Types in C++
• User Defined Data types in C++ are a type for
representing data. The data type will inform the
interpreter how the programmer will use the data.
• As the programming languages allow the user to create
their own data types according to their needs, the data
types defined by the users are known as user-defined
data types.
5. Structure
A structure is a collection of various types of related
information under one name. The declaration of structure forms a
template, and the variables of structures are known as members. All
the members of the structure are generally related. The keyword used
for the structure is “struct.”
Syntax:
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable
6. Example1:
// Create a structure variable called myStructure
struct {
int myNum;
string myString;
} myStructure;
// Assign values to members of myStructure
myStructure.myNum = 1;
myStructure.myString = "Hello World!";
// Print members of myStructure
cout << myStructure.myNum << "n";
cout << myStructure.myString << "n";
Output
1
Hello World!
7. One Structure in Multiple Variables
syntax
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3;
// Multiple structure variables separated with commas
Output
BMW X5 1999
Ford Mustang 1969
8. #include <iostream>
#include <string>
using namespace std;
int main()
{
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add
variables by separating them with a
comma here
// Put data into the first structure
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Put data into the second structure
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " <<
myCar1.model << " " <<
myCar1.year << "n";
cout << myCar2.brand << " " <<
myCar2.model << " " <<
myCar2.year << "n";
return 0;
}
9. • Named Structures
By giving a name to the structure, you can treat it as a data type. This means
that you can create variables with this structure anywhere in the program at
any
syntax
struct myDataType { // This structure is named "myDataType"
int myNum;
string myString;
};
myDataType myVar;
10. #include <iostream>
#include <string>
using namespace std;
// Declare a structure named "car"
struct car {
string brand;
string model;
int year; };
int main() {
// Create a car structure and store it
in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and
store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
11. Union
• Union is a user-defined datatype. All the members of union share
same memory location. Size of union is decided by the size of largest
member of union. If you want to use same memory location for two
or more members, union is the best for that.
• Unions are similar to structures. Union variables are created in same
manner as structure variables. The keyword “union” is used to
define unions in C language.
Syntax
union union_name {
member definition;
} union_variables;
12. Class
• A class is a user-defined data type that we can use in our program, and it
works as an object constructor, or a "blueprint" for creating objects.
• Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
• Syntax
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
13. #include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print values
cout << myObj.myNum << "n";
cout << myObj.myString;
return 0;
}
14. Access Specifiers
class MyClass { // The class
public: // Access specifier
// class members goes here
};
• The public keyword is an access specifier. Access specifiers
define how the members (attributes and methods) of a class
can be accessed.
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•protected - members cannot be accessed from outside the
class, however, they can be accessed in inherited classes.
•private - members cannot be accessed (or viewed) from
outside the class
15. Example
#include <iostream>
using namespace std;
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (x is public)
myObj.y = 50; // Not allowed (y is
private)
return 0;
}
Output
In function 'int main()':
Line 8: error: 'int MyClass::y' is private
Line 14: error: within this context
16. • An enum is a special type that represents a group of constants
(unchangeable values)
syntax
enum Level {
LOW,
MEDIUM,
HIGH
};
To create an enum, use the enum keyword, followed by the
name of the enum, and separate the enum items with a
comma:
• Note that the last item does not need a comma.
• It is not required to use uppercase, but often considered as good practice.
• Enum is short for "enumerations", which means "specifically listed".
17. • To access the enum, you must create a variable of it.
• Inside the main() method, specify the enum keyword,
followed by the name of the enum (Level) and then the
name of the enum variable (myVar in this example):
By default, the first item (LOW) has the value 0, the second
(MEDIUM) has the value 1, etc.
If you now try to print myVar, it will output 1, which
represents MEDIUM:
18. Example
enum Level {
LOW,
MEDIUM,
HIGH
};
int main() {
// Create an enum variable and
assign a value to it
enum Level myVar = MEDIUM;
// Print the enum variable
printf("%d", myVar);
return 0;
}
Output
1
19. Change Values
• As you know, the first item of an enum has the value 0. The second has the
value 1, and so on.
• To make more sense of the values, you can easily change them:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
20. Example
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
int main() {
enum Level myVar = MEDIUM;
printf("%d", myVar);
return 0;
}
Output
50
21.
22. C++ Storage Classes are used to describe the characteristics of a
variable/function. It determines the lifetime, visibility, default value, and
storage location which helps us to trace the existence of a particular variable
during the runtime of a program. Storage class specifiers are used to specify
the storage class for a variable.
Syntax
• storage_class var_data_type var_name;
C++ uses 4 storage classes, which are as follows:
• auto Storage Class
• register Storage Class
• extern Storage Class
• static Storage Class
23.
24.
25. Derived Data Types
The data-types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of four types namely:
• Function
• Array
• Pointers
• References
26. C++ Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
• C++ provides some pre-defined functions, such as main(),
which is used to execute code.
• But you can also create your own functions to perform certain actions.
• To create (often referred to as declare) a function, specify the name of the
function, followed by parentheses ():
27. Syntax
void myFunction() {
// code to be executed
}
Example
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
Output
I just got executed!
28. #include <iostream>
usingnamespacestd;
// max here is a function derived type
intmax(intx, inty)
{
if(x > y)
returnx;
else
returny;
}
// main is the default function derived
type
intmain()
{
inta = 10, b = 20;
// Calling above function to
// find max of 'a' and 'b'
intm = max(a, b);
cout << "m is "<< m;
return0;
}
Output
m is 20
29. Array
An array is a collection of items stored at continuous memory locations. The
idea of array is to represent many instances in one variable.
Syntax:
DataType ArrayName[size_of_array];
30. C++ Arrays
• Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
• To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:
string cars[4];
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
Output
Volvo
32. Pointers
Pointers are symbolic representation of addresses. They enable
programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures. It’s general declaration in C/C++
has the format:
Syntax:
datatype *var_name;
Example:
int *ptr;
ptr points to an address which holds int data
33. #include <iostream>
using namespace std;
void geeks()
{
int var = 20;
// Pointers Derived Type
// declare pointer variable
int* ptr;
// note that data type of ptr
// and var must be same
ptr = &var;
// assign the address of a variable
// to a pointer
cout << "Value at ptr = "
<< ptr << "n";
cout << "Value at var = "
<< var << "n";
cout << "Value at *ptr = "
<< *ptr << "n";
}
// Driver program
int main()
{
geeks();
}
Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
34. Reference
• When a variable is declared as reference, it becomes an alternative name for
an existing variable. A variable can be declared as reference by putting ‘&’ in
the declaration
35. #include <iostream>
usingnamespacestd;
intmain()
{
intx = 10;
// Reference Derived Type
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = "<< x << endl;
// Value of x is now changed to 30
x = 30;
cout << "ref = "<< ref << endl;
return0;
}
Output:
x = 20
ref = 30
36. C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different
keywords), for example:
•int - stores integers (whole numbers), without decimals, such as 123 or -
123
•double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
•char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes
•string - stores text, such as "Hello World". String values are surrounded by
double quotes
•bool - stores values with two states: true or false
37. Declaring (Creating) Variables
syntax
type variableName = value;
Example
#include <iostream>
using namespace std;
int main() {
int myNum = 15;
cout << myNum;
return 0;
}
Output
15
38. Rules For Declaring Variable
• The name of the variable contains letters, digits, and underscores.
• The name of the variable is case sensitive (ex Arr and arr both are different
variables).
• The name of the variable does not contain any whitespace and special
characters (ex #,$,%,*, etc).
• All the variable names must begin with a letter of the alphabet or an
underscore(_).
• We cannot used C++ keyword(ex float,double,class)as a variable name.
Valid variable names:
int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
39.
40. Dynamic Initialization
• In this method, the variable is assigned a value at the run-time.
• The value is either assigned by the function in the program or by the user at
the time of running the program.
• The value of these variables can be altered every time the program runs.
int main() {
float p,r,t;
cout<<"principle amount, time and rate"<<endl;
cout<<"2000 7.5 2"<<endl;
simple_interest s1(2000,7.5,2);//dynamic initialization
s1.display();
return 1;
}
41. C++ operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Insertion operator <<
Extraction operator >>
Scope resolution operator ::
Pointer to member declarator ::*
declare pointer to member of a class
Pointer to member operator ->*
to access a member using a pointer to
the object and a pointer to that member
Pointer to member operator .*
To access a member using object name
and a pointer to that member
Memory release operator delete
Line feed operator endl
Memory allocation operator new
Field width operator setw
42. Dereference Operator
Dereferencing is the method where we are using a pointer to
access the element whose address is being stored. We use the
* operator to get the value of the variable from its address.
Example:
int a;
// Referencing
int *ptr=&a;
// Dereferencing
int b=*ptr;
43. #include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 10, b = 20;
int* pt;
pt = &a;
cout << "The address where a is stored is: " << pt
<< endl;
cout << "The value stored at the address by "
"dereferencing the pointer is: "
<< *pt << endl;
}
44. Output
The address where a is stored is: 0x7ffdcae26a0c
The value stored at the address by dereferencing the
pointer is: 10
45. C++ Manipulator setw
• C++ manipulator setw function stands for set width. This manipulator is used
to specify the minimum number of character positions on the output field a
variable will consume.
• This manipulator is declared in header file <iomanip>.
Syntax
/*unspecified*/ setw (int n);
• n: number of characters to be used as filed width.
46. #include <iostream>
#include <iomanip>
using namespace std;
int main (void)
{
int a,b;
a = 200;
b = 300;
cout << setw (5) << a << setw (5) << b
<< endl;
cout << setw (6) << a << setw (6) << b
<< endl;
cout << setw (7) << a << setw (7) << b
<< endl;
cout << setw (8) << a << setw (8) << b
<< endl;
return 0;
}
Output
47. • If we assume the values of the variables as
2597
14
175
• respectively m=2597; n=14; p=175
• It was want to print all nos in right justified way use setw which specify a
common field width for all the nos.
48. Scope resolution operator in C++
#include <iostream>
using namespace std;
class A {
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun() { cout << "fun() called"; }
int main()
{
A a;
a.fun();
return 0;
}
Output
fun() called
49. Memory management is a process of managing computer memory, assigning
the memory space to the programs to improve the overall system
performance.
A new operator is used to create the object while a delete operator is used to
delete the object.
syntax
pointer_variable = new data-type
int *p;
p = new int;
In the above example, 'p' is a pointer of type int.
50. float *q;
q = new float;
'q' is a pointer of type float.
In the above case, the declaration of pointers and their assignments are done
separately. We can also combine these two statements as follows:
int *p = new int;
float *q = new float;
We can assign the value to the newly created object by simply using the
assignment operator.
*p = 45;
*q = 9.8;
We can also assign the values by using new operator which can be done as
follows:
pointer_variable = new data-type(value);
int *p = new int(45);
float *p = new float(9.8);
When memory is no longer required, then it needs to be
deallocated so that the memory can be used for another
purpose. This can be achieved by using the delete
operator
51. When memory is no longer required, then it needs to be deallocated so
that the memory can be used for another purpose. This can be achieved
by using the delete operator
delete pointer_variable;
Example
delete p;
delete q;
52. CONTROL STRUCTURES:
The if statement:
The if statement is implemented in
two forms:
1. simple if statement
2. if… else statement
Simple if statement:
if (condition)
{
Action;
}
If.. else statement
If (condition)
{
Statment1
}
Else
{
Statement2
}
53. Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
54. C++ has the following conditional statements:
•Use if to specify a block of code to be executed, if a
specified condition is true
•Use else to specify a block of code to be executed, if the
same condition is false
•Use else if to specify a new condition to test, if the first
condition is false
•Use switch to specify many alternative blocks of code to
be executed
55. syntax
if (condition)
{
// block of code to be executed
if the condition is true
}
example
#include <iostream>
using namespace std;
int main() {
if (20 > 18)
{
cout << "20 is greater than 18";
}
return 0;
}
Output
20 is greater than 18
56. syntax
if (condition) {
// block of code to be executed if the
condition is true
}
else {
// block of code to be executed if the
condition is false
}
Example
#include <iostream>
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
return 0;
}
Output
Good evening.
57. Syntax
if (condition1) {
// block of code to be executed if
condition1 is true
}
else if (condition2) {
// block of code to be executed if the
condition1 is false and condition2 is true
}
else {
// block of code to be executed if the
condition1 is false and condition2 is false
}
example
#include <iostream>
using namespace std;
int main()
{
int time = 22;
if (time < 10)
{
cout << "Good morning.";
}
else if (time < 20)
{
cout << "Good day.";
}
else {
cout << "Good evening.";
}
return 0;
}
58. The switch statement
This is a multiple-branching
statement where, based on
a condition, the control is
transferred to one of the
many possible points;
syntax
Switch(expr)
{
case 1:
action1;
break;
case 2:
action2;
break;
.. ..
default:
message
}
59. switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
•The switch expression is
evaluated once
•The value of the expression
is compared with the values
of each case
•If there is a match, the
associated block of code is
executed
•The break and default keyw
ords are optional, and will be
described later in this chapter
60. Example
#include <iostream>
using namespace std;
int main()
{
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
61. Example using default
#include <iostream>
using namespace std;
int main()
{
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the
Weekend";
}
return 0;
}
Output
Looking forward to the Weekend
63. Syntax
while (condition) {
// code block to be executed
}
Example
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "n";
i++;
}
return 0;
}
Output
0
1
2
3
4
64. Syntax
do {
// code block to be executed
}
while (condition);
Example
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << i << "n";
i++;
}
while (i < 5);
return 0;
}
output
0
1
2
3
4
65. For loop
When you know exactly how many times you want to loop
through a block of code, use the for loop instead of
a while loop:
syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been
executed.
68. #include <iostream>
using namespace std;
int main() {
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "n"; //
Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "n"; //
Executes 6 times (2 * 3)
}
}
return 0;
}
Output
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
69. Operator overloading
Operator overloading is a type of polymorphism in which a single operator is
overloaded to give a user-defined meaning. Operator overloading provides a
flexible option for creating new definitions of C++ operators.
In C++, we can make operators work for user-defined classes.
This means C++ has the ability to provide the operators with a special meaning
for a data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we
can concatenate two strings by just using +.
Other example classes where arithmetic operators may be overloaded are
Complex Numbers, Fractional Numbers, Big integers, etc.
71. Expression: An expression is a combination of operators, constants and
variables. An expression may consist of one or more operands, and zero
or more operators to produce a value.
72. •Constant expressions: Constant Expressions consists of only constant
values. A constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, ‘x’
•Integral expressions: Integral Expressions are those which produce integer
results after implementing all the automatic and explicit type conversions.
Examples:x, x * y, x + int( 5.0)
where x and y are integer variables.
•Floating expressions: Float Expressions are which produce floating point
results after implementing all the automatic and explicit type conversions.
Examples:x + y, 10.75
where x and y are floating point variables.
73. Relational expressions:
Relational Expressions yield results of type bool which takes a value
true or false. When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the results
compared. Relational expressions are also known as Boolean
expressions.
Examples:x <= y, x + y > 2
Logical expressions:
Logical Expressions combine two or more relational expressions and
produces bool type results.
Examples: x > y && x == 10, x == 10 || y == 5
74. Pointer expressions:
Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions:
Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers
of two.