0% found this document useful (0 votes)
13 views39 pages

Eeb 334-315 C++ Lecture 8 Ebenezer 2

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, emphasizing their roles in modeling real-world entities in programming. It explains the structure of classes, the creation of objects, and the importance of encapsulation for data protection, along with practical examples in C++. Additionally, it highlights the benefits of inheritance for code reusability and reducing redundancy in software design.

Uploaded by

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

Eeb 334-315 C++ Lecture 8 Ebenezer 2

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, emphasizing their roles in modeling real-world entities in programming. It explains the structure of classes, the creation of objects, and the importance of encapsulation for data protection, along with practical examples in C++. Additionally, it highlights the benefits of inheritance for code reusability and reducing redundancy in software design.

Uploaded by

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

EEB 334/315 COMPUTER PROGRAMMING I

By
DR. Ebenezer Esenogho
• Object Oriented Programming (OOP)
– Object-Oriented Thinking,
– Introduction to Classes,
– Objects
– Inheritance
– Polymorphism
• File Processing
Object-Oriented Thinking
• In the object-oriented thinking, we see the world as a set of
objects, and every action is a function of one of those objects.
The functional approach sees the world as a set of possible
actions, and objects only hold information.

• OOP is not the perfect way to model the world in a computer


program, but to look for the best possible illustrations for easy
understanding.

• OOP– As the name suggests uses objects in programming. OOP


aims to implement real-world entities like inheritance, hiding,
polymorphism, etc. in programming. The main aim of OOP is to
bind together the data and the functions/method that operate on
them so that no other part of the code can access this data except
that function.
OOP can be seen as a computer programming model that organizes
software design around data, or objects, rather than functions and logic. An
object can be defined as a data field that has unique attributes and
behaviour.
Data + Functions/Method =Objects
OOP binds together the data and the methods that operate on them,
encapsulating them into what we call an "object“
This mirrors real-life where objects (like cars, dogs, humans) have both
attributes (colour, breed, age) and behaviours (drive, bark, walk).
• The main structure, or building blocks of OOP

• Class
• Objects
• Encapsulation
• Abstraction
• Polymorphism
• Inheritance
• Dynamic Binding
• Message Passing

• Let‘s dive deep into these building blocks to grasp the concept of OOP .
The structure, or building blocks, of object-oriented programming include
the following:
• Classes are user-defined data types that act as the blueprint for individual
objects, attributes and methods.

• So, a class is a template for objects, and an object is an instance of a


class.
• When the individual objects are created, they inherit all the variables,
attributes and functions from that class.
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 colour, and
methods, such as drive and brake.

Attributes and methods are basically variables and functions that


belongs to the class. These are often referred to as "class members".

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.
The structure, or building blocks, of object-oriented programming
include the following:
• Classes are user-defined data types that act as the blueprint for
individual objects, attributes and methods.

– Objects are instances of a class created with specifically defined data.


Objects can correspond to real-world objects or an abstract entity. When
class is defined initially, the description is the only object that is defined.

– Methods are functions that are defined inside a class that describe the
behaviours of an object. Each method contained in class definitions starts
with a reference to an instance object. Additionally, the subroutines
contained in an object are called instance methods. Programmers use
methods for reusability or keeping functionality encapsulated inside one
object at a time.

– Attributes are defined in the class template and represent the state of an
object. Objects will have data stored in the attributes field. Class attributes
belong to the class itself.
Class:
The building block of C++ that leads to Object-Oriented
programming is a Class. It 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 (Object). A class is like
a blueprint/template for an object.

• For Example: Consider the 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. So here, the Car is the class, and
wheels, speed limits, and mileage are their properties.
Defining Class
A class is defined in C++ using the keyword class followed
by the name of the class. The body of the class is defined
inside the curly brackets and terminated by a semicolon at
the end.
//Program to create a class called book
#include <iostream>
#include <string>

// Define the Book class


class Book {
private:
// Member variables for book's title and author
std::string title;
std::string author;

public:
// Constructor to initialize the book with a title and author
Book(std::string t, std::string a) : title(t), author(a) {}

// Public method to display the book's details


void display() const {
std::cout << title << " by " << author << std::endl;
}
};

// Main function where the program execution begins


int main() {
// Create an instance of the Book class
Book myBook("1984", "George Orwell");

// Use the display method to show the book's details


myBook.display(); // Outputs: 1984 by George Orwell

return 0; // End the program


}
• //Program to create a class called car
#include <iostream>
#include <string>

// Define the Car class


class Car {
private:
// Member variables for car's brand, model, year, and color
std::string brand;
std::string model;
int year;
std::string color;

public:
// Constructor to initialize the car with its attributes
Car(std::string b, std::string m, int y, std::string c)
: brand(b), model(m), year(y), color(c) {}

// Public method to display the car's details


void showDetails() const {
std::cout << year << " " << color << " " << brand << " " << model << "." << std::endl;
}
};

// Main function where the program execution begins


int main() {
// Create an instance of the Car class
Car myCar("Toyota", "Corolla", 2022, "Red");

// Use the showDetails method to display the car's details


myCar.showDetails(); // Outputs: 2022 Red Toyota Corolla.

return 0; // End the program


}
Objects
• An Object is an identifiable entity with some characteristics and
behaviour. An Object is an instance of a Class. When a class is
defined, no memory is allocated but when an object is created
memory is allocated.

• Declaring Objects
• When a class is defined, only the specification for the object is
defined; no memory or storage is allocated. To use the data and
access functions defined in the class, you need to create objects.

• Syntax
• ClassName ObjectName;

• Note from a class, we can create multiple objects


//Create a single object called "myObj" and access the attributes:

#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;
}
// create an object myCircle. The area of this circle is then computed and displayed using its area method.
#include <iostream>

// Define the Circle class


class Circle {
private:
double radius; // Private attribute to hold the circle's radius

public:
// Constructor to initialize the radius of the circle
Circle(double r) : radius(r) {}

// Method to calculate and return the area of the circle


double area() const {
return 3.14159 * radius * radius;
}
};

// Main function where the program execution begins


int main() {
// Create an object of the Circle class with a radius of 5.0
Circle myCircle(5.0);

// Display the area of the circle using the area method


std::cout << "Area of the circle: " << myCircle.area() << std::endl; // Outputs: Area of the circle: 78.5398

return 0; // End the program


}
Creating Multiple Objects

#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
#include <iostream>
#include <string>
using namespace std;

class Car {
public:
Car(string b, string m, int y) : brand(b), model(m), year(y) {}
void display() {
cout << brand << " " << model << " " << year << "\n";
}
private:
string brand;
string model;
int year;
};

int main() {
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

carObj1.display();
carObj2.display();

return 0;
Assignment 1.

Write a C++ program to create four Objects from these classes.


Following the example above.
Using class like:
a) Computer,
b) Person
c) Animal
d) Shapes

Choose any of these class.


Will inform you when to submit.
• Encapsulation
• As seen in your book/car class, the attributes are private. This
means they cannot be accessed directly from outside the class.
Instead, you can provide public methods (getters and setters) to
access and modify these attributes, if needed. This is a key
concept in encapsulation.

• Let’s take a real-life example and try to understand it more clearly:


Assume you have an account in the bank. If you declare your
balance variable as public in the bank software, your account
balance will be public. In this scenario, anyone can know your
account balance. So, do you want it? Clearly, no.
As a result, they define the balance variable as private to protect
your account and ensure that no one can see your account
balance.

The person who needs to check his account balance will only be
able to access private members via methods defined inside that
class, and this method will demand your account holder's name
and password for authentication.
As a result, we can achieve security by using the principle of data
hiding. This is known as encapsulation.
• So, 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.

• In other words, to access Private Members/private attribute, use


public "get" and "set" methods:

• Encapsulation restricts access to certain components of an object.


Here's a simple example using a Person class

• In this code, the Person class encapsulates the name and age
attributes. External access to these attributes is controlled using
getter and setter methods.
#include <iostream>
#include <string>

// Define the Person class to demonstrate encapsulation


class Person {
private:
// Private attributes
std::string name;
int age;

public:
// Constructor to initialize the person's attributes
Person(std::string n, int a) : name(n), age(a) {}

// Getter method for the name (allows reading the private attribute 'name')
std::string getName() const {
return name;
}

// Setter method for the name (allows modifying the private attribute 'name')
void setName(const std::string &n) {
name = n;
}

// Getter method for age


int getAge() const {
return age;
// Setter method for age
void setAge(int a) {
if (a > 0) { // Basic validation to ensure age is positive
age = a;
}
}
};

// Main function to demonstrate encapsulation in action


int main() {
// Create a Person object
Person person("Alice", 25);

// Access and display the person's name using the getter


std::cout << person.getName() << " is " << person.getAge() << " years old." << std::endl; // Outputs: Alice is 25
years old.

// Modify the person's age using the setter


person.setAge(30);

// Display the updated age


std::cout << person.getName() << " is now " << person.getAge() << " years old." << std::endl; // Outputs: Alice is
now 30 years old.

return 0;
#include <iostream>
using namespace std;

class Employee {
private:
int salary;

public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(10000);
cout << myObj.getSalary();
return 0;
}
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 50000. Then we call the getSalary() method on the object
to return the value.
Inheritance.

The 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.

It allows a class to inherit properties and methods from another


class. This promotes code reusability and establishes a natural
hierarchy between classes.

Lets look at some real world examples


Example 1: A real-life example of inheritance is a child and parents.
All the properties of the father are inherited by his son
.
• Example 2:

Dog, Cat, Cow can be Derived Class of Animal Base Class


• Inheritance as a process in which, new classes are created from
the existing classes. The new class created is called “derived
class” or “child class” and the existing class is known as the
“base class” or “parent class”. The derived class now is said to
be inherited from the base class.

• When we say derived class inherits the base class, it means, the
derived class inherits all the properties of the base class, without
changing the properties of base class and may add new features
to its own. These new features in the derived class will not affect
the base class. The derived class is the specialized class for the
base class.

• Sub Class: The class that inherits properties from another class is
called Subclass or Derived Class or Child Class.
• Super Class: The class whose properties are inherited by a
subclass is called Base Class or Superclass or Parent Class.
• Why and when to use inheritance?
• Consider a group of vehicles. You need to create classes for Bus,
Car, and Truck. The methods fuelAmount(), capacity(),
applyBrakes() will be the same for all three classes. If we create
these classes avoiding inheritance then we have to write all of
these functions in each of the three classes as shown below figure:
You can clearly see that the above process results in duplication of
the same code 3 times. This increases the chances of error and data
redundancy. To avoid this type of situation, inheritance is used. If we
create a class Vehicle and write these three functions in it and inherit
the rest of the classes from the vehicle class, then we can simply
avoid the duplication of data and increase re-usability. Look at the
below diagram in which the three classes are inherited from vehicle
class:

Common
characteristics
Using inheritance, we have to write the functions only one time instead
of three times as we have inherited the rest of the three classes from the
base class (Vehicle).

Syntax:

class <derived_class_name> : <access-specifier> <base_class_name>


{
//body
}

To inherit from a class, use the : symbol.

Example 1. the Car class (child) inherits the attributes and methods from the Vehicle
class (parent)

Example 2. demonstrates inheritance. In this example, we will define a base class


Person and a derived classes/sub-class/child class Student.
#include <iostream>
#include <string>
using namespace std;

// Base class definition


class Vehicle {
public:
// Default brand for all vehicles
string brand = "Ford";

// Method to make the vehicle honk


void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class that represents a more specific type of vehicle


class Car: public Vehicle {
public:
// Model specific to the car
string model = "Mustang";
};

int main() {
// Creating an object of the Car class
Car myCar;

// Using the honk method from the Vehicle class (inherited by Car)
myCar.honk();

// Displaying the brand (from Vehicle) and model (from Car) of myCar
cout << myCar.brand + " " + myCar.model;

return 0;
}
#include <iostream>
#include <string>
using namespace std;

// Base class definition


class Person {
public:
string name;
int age;

Person(string n, int a) : name(n), age(a) {}

virtual void display() {


cout << "Name: " << name << ", Age: " << age << endl;
}
};

class Student : public Person {


public:
string major;

Student(string n, int a, string m) : Person(n, a), major(m) {}

// Overriding the display method to add major


void display() override {
cout << "Name: " << name << ", Age: " << age << ", Major: " << major << endl;
}
};

int main() {
Student stu("Alice", 20, "Computer Science");
stu.display();

return 0;
}
Types Of Inheritance:-
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance.
Polymorphism:
• In the C++ OOPs concept, polymorphism means taking more than
one form. For example, imagine you are in a classroom at that
time. You behave like a student. When you are in the market at
that time, you behave like a customer/trader. When you are at
your home at that time, you behave like a son or daughter. In this
case, one person is exhibiting a variety of behaviours.

• Polymorphism means many forms. It is an object-oriented


programming concept that refers to the ability of a variable,
function, or object to take on multiple forms, which are when the
behaviour of the same object or function is different in different
contexts.

• Polymorphism can occur within the class and when multiple


classes are related by inheritance..
In the C++ OOPs concept, we use Operator overloading and
Function overloading to achieve polymorphism.
The + operator in C++ is one of the best examples of polymorphism.
Here it used to add two integers
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 32;

cout << "Value of a + b is: " << a + b;


return 0;
}
In the above example, ”+” is used to add a=10 and b=32, the output
Value of a+b is : 42.
However, + is also used to concatenate two string operands. The +
operator is used to concatenate two strings as follows :
(The + operator is used to add two integers as follows)
#include <iostream>
using namespace std;

int main() {
string a = "poly";
string b = "morphism";
cout << "Value of a + b is: " << a + b;
return 0;
}
//output is Value of a + b is: polymorphism
Thank you

Kea leboga
Abstraction

You might also like