CH 1 OOP - Introduction
CH 1 OOP - Introduction
CH 1 OOP - Introduction
Introduction to Object-Oriented
Programming (OOP) in C++
1.1 Overview of Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that uses 'objects' to
design applications and computer programs. It incorporates several principles and concepts
such as:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Objects:
Objects are instances of classes. They contain data (attributes) and methods (functions) that
manipulate the data.
Classes:
A class is a blueprint for creating objects. It defines a datatype by bundling data and
methods.
Encapsulation:
Encapsulation is the mechanism of restricting access to some of the object's components. It
means that the internal representation of an object is hidden from the outside. Achieved
using access specifiers: private, protected, and public.
Inheritance:
Inheritance is a way to form new classes using classes that have already been defined. The
new class (derived class) inherits attributes and methods from the existing class (base
class). Promotes code reuse.
Polymorphism:
Polymorphism allows methods to do different things based on the object it is acting upon.
Achieved through method overloading and method overriding.
Abstraction:
Abstraction is the concept of hiding the complex implementation details and showing only
the necessary features. Achieved using abstract classes and interfaces.
Chapter 1 – Introduction to OOP in C++ Author: Irfan
#include <iostream>
using namespace std;
// Class Definition
class Car {
public:
string brand;
string model;
int year;
void printDetails() {
cout << "Brand: " << brand << "\nModel: " << model <<
Chapter 1 – Introduction to OOP in C++ Author: Irfan
// Main Function
int main() {
// Creating an object of Car
Car car1;
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2020;
// Accessing method
car1.printDetails();
return 0;
}
Example:
class Box {
private:
double length;
public:
double width;
protected:
double height;
};
- Destructor:
- Special function called when an object is destroyed.
Chapter 1 – Introduction to OOP in C++ Author: Irfan
Example:
class Box {
public:
double length;
Box() {
length = 0.0;
}
~Box() {
// Destructor code
}
};
Example:
class Shape {
public:
void setWidth(int w) {
width = w;
}
protected:
int width;
};
- Run-time Polymorphism:
- Virtual Functions
Example:
class Base {
public:
virtual void show() {
cout << "Base class" << endl;
}
};
int main() {
Base* b;
Derived d;
b = &d;
b->show(); // Outputs: Derived class
return 0;
}