Show 25 50 100
PDF
12 result(s) in OOP Clear

Index

Showing 12 topics
  1. OOP, Class and Object
  2. Constructor and Destructor
  3. Encapsulation
  4. Access Specifiers
  5. Inheritance
  6. Polymorphism
  7. Abstraction and Abstract Class
  8. Interface vs Abstract Class
  9. this Pointer and Static Members
  10. Friend Function and Operator Overloading
  11. SOLID Principles
  12. Association, Aggregation, Composition
1 Index

OOP (Object Oriented Programming) organises a program around objects that hold data (attributes) and behaviour (methods) together.

Class is the blueprint; object is a real instance created from it. Example: class Car → objects myCar, yourCar.

Encapsulation, Abstraction, Inheritance, Polymorphism

Encapsulation, Abstraction, Inheritance, Polymorphism

C++ 16 lines
class Car {
public:
    string brand;       // attribute
    int speed;

    void drive() {      // method
        cout << brand << " is driving at " << speed << " km/h\n";
    }
};

int main() {
    Car c1;             // object
    c1.brand = "Toyota";
    c1.speed = 80;
    c1.drive();
}

Q & A

  1. Does a class take memory?
    No. Memory is allocated only when an object is created.
  2. Advantages of OOP?
    Reusability (inheritance), security (encapsulation), easy maintenance, real-world modelling and flexibility (polymorphism).
2 Index

A constructor has the same name as the class, no return type, and runs automatically when an object is created. A destructor (~ClassName) runs when the object is destroyed.

  • Default constructor — no parameters.
  • Parameterised constructor — takes arguments.
  • Copy constructor — creates an object from another object: Student(const Student &s).
  • Constructors can be overloaded; a destructor cannot (only one, no parameters).
C++ 13 lines
class Student {
    string name;
    int roll;
public:
    Student() : name("Unknown"), roll(0) {}                 // default
    Student(string n, int r) : name(n), roll(r) {}          // parameterised
    Student(const Student &s) : name(s.name), roll(s.roll) {} // copy
    ~Student() { cout << name << " destroyed\n"; }          // destructor
};

Student a;               // default
Student b("Rahim", 7);   // parameterised
Student c = b;           // copy

Q & A

  1. Can a constructor be private?
    Yes. It stops outside code from creating objects directly, used for example in the Singleton pattern.
  2. Shallow vs deep copy?
    A shallow copy copies pointer values, so both objects share the same memory. A deep copy allocates new memory and copies the data.
3 Index

Wrapping data and methods into a single unit (class) and hiding the data with private. Outside code uses public getters and setters, which can validate values.

C++ 14 lines
class BankAccount {
private:
    double balance = 0;          // hidden
public:
    void deposit(double amount) {
        if (amount > 0) balance += amount;   // validation
    }
    double getBalance() const { return balance; }
};

BankAccount acc;
acc.deposit(500);
// acc.balance = 1000000;   // error: balance is private
cout << acc.getBalance();    // 500
4 Index
SpecifierSame classChild classOutside
public✔✔✔
protected✔✔✘
private✔✘✘

Note: in C++ class members are private by default; struct members are public by default.

5 Index

A child (derived) class gets the members of a parent (base) class, so code is reused. It models an is-a relationship: a Dog is an Animal.

Single, multilevel, multiple and hierarchical inheritance

Single, multilevel, multiple and hierarchical inheritance

C++ 13 lines
class Animal {
public:
    void eat() { cout << "Eating\n"; }
};

class Dog : public Animal {      // Dog inherits Animal
public:
    void bark() { cout << "Barking\n"; }
};

Dog d;
d.eat();    // from Animal
d.bark();   // own method

Q & A

  1. What is the diamond problem?
    In multiple inheritance, if B and C both inherit A and D inherits B and C, D gets two copies of A. C++ solves it with virtual inheritance (class B : virtual public A).
  2. Constructor call order in inheritance?
    Parent constructor runs first, then child. Destructors run in the reverse order: child first, then parent.
6 Index

Polymorphism means one name, many forms.

Compile-time (static)Run-time (dynamic)
Function overloading, operator overloadingFunction overriding with virtual functions
Decided by the compilerDecided while running (via vtable)
FasterMore flexible
Run-time polymorphism C++ 24 lines
class Shape {
public:
    virtual double area() { return 0; }     // virtual = can be overridden
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() override { return 3.1416 * r * r; }
};

class Square : public Shape {
    double a;
public:
    Square(double a) : a(a) {}
    double area() override { return a * a; }
};

Shape *s1 = new Circle(2);
Shape *s2 = new Square(3);
cout << s1->area();   // 12.56  → Circle's area()
cout << s2->area();   // 9      → Square's area()

Q & A

  1. Overloading vs overriding?
    Overloading: same name, different parameters, in the same class, compile time. Overriding: same signature in parent and child, run time, needs inheritance (and virtual in C++).
  2. Why should a base class destructor be virtual?
    So that deleting a child object through a base pointer also runs the child destructor; otherwise resources leak.
7 Index

Abstraction shows only the essential features and hides the details. Example: you press the brake without knowing how the brake system works.

In C++ a class with at least one pure virtual function (= 0) is an abstract class. It cannot be instantiated; child classes must implement the function.

C++ 13 lines
class Payment {                       // abstract class
public:
    virtual void pay(double amount) = 0;   // pure virtual
};

class Bkash : public Payment {
public:
    void pay(double amount) override { cout << "Paid " << amount << " by bKash\n"; }
};

// Payment p;       // error: cannot create an abstract object
Payment *p = new Bkash();
p->pay(500);
8 Index
Abstract classInterface
Can have both abstract and normal methodsOnly method declarations (Java 8+ also allows default methods)
Can have fields / state and constructorsOnly constants, no constructor
A class extends only one abstract class (Java/C#)A class can implement many interfaces
Used for closely related classes (is-a)Used for a capability (can-do), e.g. Comparable

C++ has no interface keyword: a class with only pure virtual functions acts as an interface.

Java: one class, many interfaces Java 7 lines
interface Flyable { void fly(); }
interface Swimmable { void swim(); }

class Duck implements Flyable, Swimmable {
    public void fly()  { System.out.println("Duck flies"); }
    public void swim() { System.out.println("Duck swims"); }
}
9 Index
  • this points to the current object. Used when a parameter has the same name as a member, or to return the object itself.
  • static data member — one copy shared by every object, e.g. a counter of objects.
  • static member function — called with the class name, can use only static members (no this).
C++ 14 lines
class Student {
    string name;
    static int count;          // shared
public:
    Student(string name) {
        this->name = name;     // this-> separates member from parameter
        count++;
    }
    static int total() { return count; }
};
int Student::count = 0;        // define outside the class

Student a("A"), b("B");
cout << Student::total();      // 2
10 Index

A friend function is not a member but can access private members. It is often used for operator overloading such as <<.

C++ 15 lines
class Complex {
    int re, im;
public:
    Complex(int r = 0, int i = 0) : re(r), im(i) {}

    Complex operator+(const Complex &o) const {     // member operator
        return Complex(re + o.re, im + o.im);
    }
    friend ostream& operator<<(ostream &out, const Complex &c) {
        return out << c.re << " + " << c.im << "i";
    }
};

Complex a(2, 3), b(1, 4);
cout << a + b;    // 3 + 7i
11 Index
LetterPrincipleMeaning
SSingle ResponsibilityA class should have only one reason to change.
OOpen / ClosedOpen for extension, closed for modification (add new classes, do not edit old ones).
LLiskov SubstitutionA child object must work wherever the parent is expected.
IInterface SegregationMany small interfaces are better than one big one.
DDependency InversionDepend on abstractions (interfaces), not on concrete classes.
12 Index
  • Association — a general relationship: a Teacher teaches a Student.
  • Aggregation (has-a, weak) — the part can exist alone: a Department has Teachers; if the department closes, teachers still exist.
  • Composition (has-a, strong) — the part cannot exist without the whole: a House has Rooms; delete the house, the rooms are gone.