Cheatography
https://cheatography.com
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which combine data (attributes) and functions (methods). OOP promotes modularity, reusability, and scalability, making complex software easier to develop and maintain.
This is a draft cheat sheet. It is a work in progress and is not finished yet.
Class and Objects
Class |
A user-defined data type that defines attributes (data members) and behaviors (member functions). It acts as a blueprint for objects |
Object |
An instance of a class with specific values and behaviors |
Pillars of OOP
Encapsulation |
Encapsulation is wrapping up the data and methods together within a single entity. In C++, classes are used for encapsulation. |
Abstraction |
Showing only the necessary details and hiding the internal details is known as abstraction. |
Polymorphism |
Providing different functionalities to the functions or operators of the same name is known as Polymorphism. |
Access Specifiers
• public: Accessible from outside the class.
• private: Cannot be accessed directly from outside.
• protected: Like private, but accessible in derived classes.
class Demo {
private:
int secretNumber;
public:
int publicNumber;
}; |
Class Example
class Car {
public:
string brand;
int year;
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2022;
}
|
|
|
Inheritance
Deriving the properties of a class ( Parent class ) to another class ( Child class ) is known as Inheritance. It is used for code reusabilty. |
Building a Class
Attribute (Data Members) |
variables which represent the attributes of the class |
Functionality (Member Functions) |
functions which represent the behaviors of the class |
Constructor
a special member function that is automatically called when an object of a class is created |
Object Instantiation
• Creating objects from a class.
• Accessing attributes/methods using dot syntax.
Circle c1(5.0);
cout << c1.radius; |
Demonstration
Compute circumference and area of a circle.
class Circle {
private:
double radius;
public:
Circle(double r) { radius = r; }
double getCircumference() { return 2 3.1416 radius; }
double getArea() { return 3.1416 radius radius; }
};
int main() {
Circle c1(5);
cout << "Circumference: " << c1.getCircumference();
cout << "Area: " << c1.getArea();
}
|
Class Rectangle
class Rectangle {
public:
int length, width;
int area() {
return length * width;
}
};
|
|