OBJECT-ORIENTED PROGRAMMING
What is Object-Oriented Programming?
Object-oriented programming (OOP) aims to implement real-world entities such as inheritance, hiding, and polymorphism in programming.
Unlike procedural programming, where functions are written to perform operations on data, OOP involves creating objects that contain both data and functions.
Key Concepts of Object-Oriented Programming
Object
The basic unit of object-oriented programming.
Both data and functions that operate on data are bundled as a unit called an object.
Class
A class is a blueprint for an object.
It does not define any data itself but specifies what an object will consist of and what operations can be performed on such an object.
Example: In the context of a class representing Cars, all cars share common properties such as wheels, speed limit, and mileage range.
Abstraction
Definition: Data abstraction refers to providing only essential information while hiding background details, allowing the representation of needed information without disclosing internal specifics.
Example: A database system hides details of how data is stored; similarly, C++ classes provide methods to the outside without exposing internal details.
Encapsulation
Definition: The binding together of data and the functions that operate on that data within a single unit.
Unlike procedural languages, where it is unclear which functions work on which variables, OOP clarifies this by keeping relevant functions and data together in the same object.
Inheritance
Inheritance is a process of deriving a new class from an existing class, known as the base class.
The new class is termed the derived class, promoting code reusability and reducing code size.
Polymorphism
Polymorphism allows an operator or function to be used in different ways or to function with different meanings.
The prefix "poly" indicates many. It describes a single function or operator behaving differently based on context and usage.
Class and Object Construction
Class
A user-defined data type containing its own data members and member functions accessed via creating an instance of that class.
In programming terms, a Car class contains attributes like brand and model, and methods to drive or show its data.
Member Function
Also known as methods, these define the behavior of the objects in a class.
Data Members
Also referred to as attributes, these define the properties of the objects in a class.
Creating a Class in C++
To create a class, use the
classkeyword:
class Car {
public:
string brand, model;
int mileage = 0;
void drive(int distance) { mileage += distance; }
void show_data() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Distance driven: " << mileage << " miles" << endl;
}
};
```
- Attributes like brand and model hold data, whereas functions like `drive()` manipulate this data.
- The `public` keyword denotes an access modifier to allow accessibility from outside the class.
## Object Definition
- An object is an identifiable entity with characteristics and behavior, being an instance of a class.
- Memory is allocated when an object is instantiated:
cpp
Car suv;
Car sedan;
Car van;
```
Syntax for creating objects:
class_Name object_name;
More on Encapsulation
Definition: Encapsulation is wrapping up data and functions into a single unit.
In OOP, it binds data and functions manipulating them together.
Member functions have access to their class's data, promoting data hiding by using
privateandprotectedkeywords for class members, whilepublicallows access from outside.
Abstraction Revisited
Abstraction consists of displaying only essential information while hiding details.
Implemented via classes in C++ using access specifiers to group data members and methods, dictating visibility to the outside world.
Example: The
pow()function in themath.hheader file shows abstraction as users utilize it without needing to understand the underlying algorithm.
Important Note
Abstraction is distinct from data hiding: abstraction displays relevant information, while data hiding restricts access to class members to prevent outside interference.
Inheritance Details
Inheritance enables a class to derive properties from another class:
- Sub Class/Derived Class: The class inheriting properties.
- Super Class/Base Class: The class whose properties are inherited.Supports code reusability, allowing the derived class to reuse data fields and methods from the base class without modification.
Example of Inheritance in C++
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
string brand;
void show_brand() { cout << "Brand: " << brand << endl; }
};
// Derived class
class Car : public Vehicle {
public:
string model;
void show_model() { cout << "Model: " << model << endl; }
};
int main() {
Car my_car;
my_car.brand = "Honda";
my_car.model = "Accord";
my_car.show_brand();
my_car.show_model();
}
Access Specifiers
Access specifiers define how class members are accessed:
- Public: Members are accessible from outside the class.
- Private: Members cannot be accessed from outside the class.
- Protected: Members cannot be accessed from outside the class but can be viewed in derived classes.
Example of Access Specifiers in C++
#include <iostream>
using namespace std;
class MyClass {
public:
int x, sum;
void showSum() { cout << x+y; }
private:
int y=50;
};
int main() {
MyClass myObject;
myObject.x = 25; // Allowed (public)
myObject.showSum();
return 0;
}
Protected Access Example
#include <iostream>
using namespace std;
class Parent {
protected:
int id_protected;
};
class Child : public Parent {
public:
void setId(int id) { id_protected = id; }
void displayId() { cout << "id_protected is: " << id_protected << endl; }
};
int main() {
Child object1;
}
Types of Inheritance
Multilevel Inheritance
A class can be derived from another derived class.
class MyClass {
public:
void myFunction() { cout << "Some content in parent class." ; }
};
class MyChild: public MyClass { };
class MyGrandChild: public MyChild { };
int main() {
MyGrandChild myObject;
myObject.myFunction();
}
Multiple Inheritance
A class can derive from more than one base class, joined by a comma.
class MyClass {
public:
void myFunction() { cout << "Some content in parent class." ; }
};
class MyOtherClass {
public:
void myOtherFunction() { cout << "Some content in another class." ; }
};
class MyChildClass: public MyClass, public MyOtherClass { };
int main() {
MyChildClass myObject;
myObject.myFunction();
myObject.myOtherFunction();
}
Polymorphism in Depth
Definition: The ability to present the same operation in different forms.
Example: A person exhibiting different roles such as father and employee, demonstrating polymorphism based on context.
Operator Overloading
Enables operators to exhibit different behaviors based on context.
Function Overloading
The process of defining a single function name to perform diverse operations.
Example of Polymorphism in C++
class Shape {
public:
void shape_name() { cout << "Shape" << endl; }
};
class Square : public Shape {
public:
void shape_name() { cout << "Square" << endl; }
};
int main() {
Shape shape;
Square square;
shape.shape_name(); // Outputs "Shape"
square.shape_name(); // Outputs "Square"
}
Constructors in C++
A constructor is a special method invoked when an object is created.
Constructors should have the same name as the class and no return value.
class MyClass {
public:
MyClass() {
cout << "Hello World!";
}
};
int main() {
MyClass myObject; // Invokes the constructor
}
Constructor Parameters
Constructors can take parameters to initialize attributes when an object is created.
class Car {
public:
string brand;
string model;
int year;
Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
};
int main() {
Car carObject1("BMW", "X5", 1999);
Car carObject2("Ford", "Mustang", 1969);
}
Defining Methods Outside the Class
To define a function outside the class definition, declare it within the class and define it using the scope resolution operator:
class MyClass {
public:
void myMethod();
};
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObject;
myObject.myMethod();
}
Example of Method with Parameters
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObject;
cout << myObject.speed(200); // Call the method
}