0% found this document useful (0 votes)
11 views53 pages

OOP Concepts in C++ Explained

Chapter Five discusses Object-Oriented Programming (OOP) in C++, highlighting its differences from procedural programming and its advantages such as faster execution and better code structure. It covers key concepts like classes, objects, access modifiers, constructors, destructors, encapsulation, inheritance, polymorphism, and exception handling. The chapter emphasizes the importance of OOP principles in creating modular, maintainable, and reusable code.

Uploaded by

h34547256
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)
11 views53 pages

OOP Concepts in C++ Explained

Chapter Five discusses Object-Oriented Programming (OOP) in C++, highlighting its differences from procedural programming and its advantages such as faster execution and better code structure. It covers key concepts like classes, objects, access modifiers, constructors, destructors, encapsulation, inheritance, polymorphism, and exception handling. The chapter emphasizes the importance of OOP principles in creating modular, maintainable, and reusable code.

Uploaded by

h34547256
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

Chapter Five

Object-Oriented Programming
(OOP) in C++

1
What is OOP?

• The main purpose of C++ programming was to add


object orientation to the C programming language
(which is a procedural programming).

– Procedural programming is about writing procedures or


functions that perform operations on the data.

• OOP is a methodology or paradigm to design a


program using classes and objects.

• OOP is about creating objects that contain both data


and functions.

2
OOP vs Procedural Programming

• Procedural Programming:
–It is a programming paradigm that structures code
around procedures, functions, or subroutines.

–It focuses on the sequence of steps taken to solve a


problem and emphasizes the use of functions to
modularize code.

3
OOP vs Procedural Programming

• Object-Oriented Programming:
–It is a programming paradigm that structures code
around objects and classes.

–It is a programming paradigm focuses on the data


and behavior of objects and emphasizes the use of
inheritance, polymorphism, and encapsulation

4
OOP vs Procedural Programming

• Object-oriented programming has several advantages


over procedural programming:
– OOP is faster and easier to execute
– OOP provides a clear structure for the programs
– OOP helps to keep the C++ code DRY "Don't Repeat
Yourself", and makes the code easier to maintain, modify
and debug
– OOP makes it possible to create full reusable
applications with less code and shorter development
time

5
C++ Class and Object

▪ In C++, class is a group of similar objects.

▪ It is a template from which objects are created.

▪ A class is used to specify the form of an object and it


combines data representation and methods for
manipulating that data into one neat package.

▪ The data and functions within a class are called


members of the class.

6
C++ Class Definitions

▪ When you define a class, you define a blueprint for a


data type.

▪ This doesn't actually define any data, but it does


define what the class name means, that is,
▪ what an object of the class will consist of and

▪ what operations can be performed on such an object.

7
C++ Class Definitions
• A class definition starts with the keyword class
followed by the class name; and the class body,
enclosed by a pair of curly braces.
• A class definition must be followed either by a
semicolon (;) or a list of declarations.

8
Define C++ Object

▪ A class provides the blueprints for objects, so basically


an object is created from a class and it is an instance of
a class.
▪ We declare objects of a class with exactly the same sort
of declaration that we declare variables of basic types.
▪ All the members of the class can be accessed through object.
▪ Object is a runtime entity, it is created at runtime.

▪ In this example
▪ Student is the type and stud and s are the reference variables
(objects) that refers to the instance of Student class.
▪ Both objects will have their own copy of data members. 9
Accessing the Data Members

▪ The public data


members of objects of a
class can be accessed
using the direct member
access operator (.).

output

10
Define Class Member Function
▪ A member function of a class is a function that has its
definition or its prototype within the class definition.
▪ It operates on any object of the class of which it is a
member, and has access to all the members of a class
for that object.
▪ Member functions can be defined within the class
definition or separately (outside the class) using scope
resolution operator (::).
▪ Here, only important point is that you would have to
use class name just before :: operator.

11
Defining Member Function inside class

member function definition

12
Accessing Member Function

Accessing member function


definitions using dot (.) operator

output

13
Defining Member Function outside class

14
Accessing Member Function

Output:

15
C++ Class Access Modifiers
▪ Data hiding is one of the important features of OOP
which allows preventing the functions of a program to
access directly the internal representation of a class
type.
▪ Access specifiers in C++ are keywords used to specify
the access rules for the members of a class.
▪ There are three access specifiers:
1. Public
2. Private
3. Protected

▪ The default access for members and classes is private. 16


C++ Class Access Modifiers
1. Public:
▪ A public member is accessible from anywhere outside the
class but within a program.
2. Private:
▪ A private member variable or function cannot be
accessed, or even viewed from outside the class.
▪ Only the class and friend functions can access private
members.
3. Protected:
▪ A protected member variable or function is very similar
to a private member but it provided one additional
benefit that they can be accessed in child classes which
are called derived classes.
17
C++ Class Access Modifiers: Example

18
C++ Class Access Modifiers: Example

Output

19
C++ Constructor

▪ Constructor is a special method which is invoked


automatically at the time of object creation.
▪ It is used to initialize the data members of new object
generally.
▪ The constructor in C++ has the same name as class or
structure.
• There can be two types of constructors in C++.
– Default Constructor
– Parameterized Constructor

20
C++ Constructor
• Default Constructor is a
constructor which has
no argument.
• It is invoked at the time
of creating object.

Output

Default Constructor Invoked


Default Constructor Invoked

21
C++ Constructor
• Parameterized
Constructor is a
constructor which
has parameters.
• It is used to provide
different values to
distinct objects.

Output

101 Miki 5000


102 Elsa 8000

22
C++ Destructor

• A destructor works opposite to constructor; it


destructs the objects of classes.
• It can be defined only once in a class.
• Like constructors, it is invoked automatically.
• A destructor is defined like constructor.
• It must have same name as class, but it is prefixed
with a tilde sign (~).

23
C++ Constructor and Destructor: Example

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

24
C++ this Pointer

• In C++ programming, this is a keyword that refers to


the current instance of the class.
• There can be 3 main usage of this keyword in C++.
– It can be used to pass current object as a parameter to
another method.
– It can be used to refer current class instance variable.
– It can be used to declare indexers.

25
C++ this Pointer Example

Output:

101 Chala 45000


102 Yaya 15000

26
C++ static

• In C++, static is a keyword or modifier that belongs to the type


not instance.
• So instance is not required to access the static members.
• In C++, static can be field, method, constructor, and class.

Advantage of static keyword


❖ Memory efficient: Now we don't need to create instance for accessing the
static members, so it saves memory.

27
Static Field

• A field which is declared as static is called static field.

• Unlike instance field which gets memory each time


whenever you create object, there is only one copy of
static field created in the memory.

• It is shared to all the objects.

28
Static Field

Output:

222 Eric 5.5


223 Rahul 5.5

29
C++ Encapsulation

▪ The meaning of Encapsulation, is to make sure that


"sensitive" data is hidden from users.
▪ To achieve this, you must declare class
variables/attributes as private (cannot be accessed
from outside the class).
▪ If you want others to read or modify the value of a
private member, you can provide public get and set
methods.
▪ To access a private attribute, use public "get" and "set"
methods.

30
C++ Encapsulation

▪ Why Encapsulation?
▪ It ensures better control of your data, because you
(or others) can change one part of the code without
affecting other parts.
▪ It increases security of data

31
C++ Encapsulation: Example

32
C++ Encapsulation: Example

• The salary attribute is private, which have restricted access.


• The public setSalary() method takes a parameter (s) and
assigns it to the salary attribute (salary = s).
• The public getSalary() method returns the value of the
private salary attribute.
• Inside main(), we create an object of the Employee class.
Now we can use the setSalary() method to set the value of
the private attribute to 20000.
• Then we call the getSalary() method on the object to return
the value.

33
C++ Inheritance

• Inheritance is the process of creating new classes, called


derived classes, from existing or base class.
• We group the "inheritance concept" into two
categories:
– derived class (child) - the class that inherits from another class
– base class (parent) - the class being inherited
• To inherit from a class, use the : symbol.

Inherited three classes (Bus, Car,


Truck) from the base class (Vehicle).

34
C++ Inheritance
• Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
• Where
– class — keyword to create a new class
– derived_class_name — name of the new class, which will
inherit the base class
– access-specifier — either of private, public or protected. If
neither is specified, PRIVATE is taken as default
– base-class-name — name of the base class

35
C++ Inheritance

• A derived class doesn’t inherit access to private data


members. However, it does inherit a full parent
object, which contains any private members which
that class declares.

• Example
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }

36
C++ Inheritance

• When a base class is privately inherited by the derived


class, public members of the base class becomes the
private members of the derived class.

• Therefore, the public members of the base class can


only be accessed by the member functions of the
derived class.

• They are inaccessible to the objects of the derived


class.
37
C++ Inheritance

• On the other hand, when the base class is publicly


inherited by the derived class, public members of the
base class also become the public members of the
derived class.

• Therefore, the public members of the base class are


accessible by the objects of the derived class as well as
by the member functions of the derived class.

38
C++ Inheritance: Example

39
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is
allowed to inherit from only one class. i.e. one subclass
is inherited by one base class only.

40
Types of Inheritance in C++
2. Multiple Inheritance: a class can inherit from more
than one class. i.e one subclass is inherited from more
than one base class.

41
Types of Inheritance in C++

3. Multilevel Inheritance: In this type of inheritance, a


derived class is created from another derived class.

42
Types of Inheritance in C++

3. Multilevel Inheritance: In this type of inheritance, a


derived class is created from another derived class.

43
Types of Inheritance in C++
4. Hierarchical Inheritance: more than one subclass is
inherited from a single base class. i.e. more than one
derived class is created from a single base class.

44
Types of Inheritance in C++
4. Hierarchical Inheritance: more than one subclass is
inherited from a single base class. i.e. more than one
derived class is created from a single base class.

45
Polymorphism in C++
• The word “polymorphism” means having many forms.
• We can define polymorphism as the ability of a
message to be displayed in more than one form.
– A real-life example of polymorphism is a person who at
the same time can have different characteristics.
– A man at the same time is a father, a husband, and an
employee. So the same person exhibits different behavior
in different situations.
– This is called polymorphism.
• Types of Polymorphism
– Compile-time Polymorphism
– Runtime Polymorphism
46
Compile-time Polymorphism
• This type of polymorphism is achieved by function
overloading or operator overloading.
A. Function Overloading
–When there are multiple functions with the same
name but different parameters, then the functions
are said to be overloaded, hence this is known as
function overloading.
–Functions can be overloaded by changing the
number of arguments or/and changing the type of
arguments.

47
Compile-time Polymorphism
• This type of polymorphism is achieved by function
overloading or operator overloading.

B. Operator Overloading
–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, single operator ‘+’, when placed
between integer operands, adds them and when
placed between string operands, concatenates
them.

48
Runtime Polymorphism

• This type of polymorphism is achieved by function


overriding.
Function Overriding
–Function Overriding occurs when a derived class
has a definition for one of the member functions of
the base class.
–That base function is said to be overridden.

49
Runtime Polymorphism

• This type of polymorphism is achieved by function


overriding.

50
Exception Handling in C++

• An exception is an unexpected problem that arises during


the execution of a program our program terminates
suddenly with some errors/issues.
• Exception occurs during the running of the program
(runtime)..
• There are two types of exceptions in C++
– Synchronous: Exceptions that happen when something
goes wrong because of a mistake in the input data or
when the program is not equipped to handle the current
type of data it’s working with, such as dividing a number
by zero.
– Asynchronous: Exceptions that are beyond the program’s
control, such as disc failure, keyboard interrupts, etc.
51
C++ try and catch
• C++ provides an inbuilt feature for Exception Handling.
• It can be done using the following specialized keywords:
try, catch, and throw with each having a different
purpose.
• Syntax
try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown from
try block
}

52
Thank You

?
53

You might also like