3AID4-06 · RTU · 2nd Year
Object Oriented Programming
Learn OOP concepts using C++ including classes, inheritance, polymorphism, and exception handling
Last time you stopped at card —. ·
- 20cards
- 5units
- 0nailed
- 13diagrams
20/20
-
OOP = Programming paradigm based on objects containing data and code.
4 Pillars:
- 1. Encapsulation - Bundling data + methods
- 2. Abstraction - Hiding complexity
- 3. Inheritance - Reusing code from parent
- 4. Polymorphism - Many forms, same interface
Key Concepts:
- Class = Blueprint
- Object = Instance of class
- Method = Function in class
- Attribute = Variable in class
Benefits:
✓ Modular code
✓ Code reuse
✓ Easy maintenance
✓ Real-world modeling
-
Aspect Procedural OOP Focus Functions/procedures Objects Data Separate from functions Bundled with methods Access Global/local Private/public/protected Reuse Function calls Inheritance Security Less secure More secure (encapsulation) Procedural: C, Pascal, BASIC
OOP: C++, Java, Python
When to use:
- Procedural: Small scripts, simple tasks
- OOP: Large projects, team development
-
Class = Blueprint/template for objects
Object = Instance of a class
// Class definition class Student { private: string name; int roll; public: void setData(string n, int r) { name = n; roll = r; } void display() { cout << name << " " << roll; } }; int main() { Student s1; // Object created s1.setData("John", 101); s1.display(); }Memory: Class = No memory, Object = Uses memory
-
Access Specifiers control visibility of class members.
Specifier Class Derived Outside public ✓ ✓ ✓ protected ✓ ✓ ✗ private ✓ ✗ ✗ class Example { public: int a; // Accessible everywhere protected: int b; // Class + children private: int c; // Only this class };Default: private in class, public in struct
Best Practice: Make data private, methods public
-
Constructor = Special method called automatically when object is created.
Rules:
- Same name as class
- No return type
- Called automatically
- Can be overloaded
Types:
- 1. Default - No parameters
- 2. Parameterized - With parameters
- 3. Copy - Creates copy of object
class Student { public: Student() { } // Default Student(int r) { roll = r; } // Parameterized Student(Student &s) { roll = s.roll; } // Copy }; -
Copy Constructor = Creates new object as copy of existing object.
class Box { int length; public: Box(int l) { length = l; } // Copy Constructor Box(Box &b) { length = b.length; } }; int main() { Box b1(10); Box b2 = b1; // Copy constructor called Box b3(b1); // Also copy constructor }When called:
- Object initialized from another
- Passed by value to function
- Returned by value from function
Shallow vs Deep Copy needed for pointers!
-
Destructor = Special method called when object is destroyed.
Syntax: ~ClassName()
class File { FILE* fp; public: File(string name) { fp = fopen(name.c_str(), "r"); } ~File() { // Destructor fclose(fp); cout << "File closed!"; } };Rules:
- Same name as class with ~
- No parameters
- No return type
- Cannot be overloaded
- Called automatically
Use for: Cleanup, freeing memory, closing files
-
Static Members = Shared across all objects of class.
class Counter { public: static int count; // Static variable Counter() { count++; } static int getCount() { // Static function return count; } }; int Counter::count = 0; // Initialize outside int main() { Counter c1, c2, c3; cout << Counter::getCount(); // Output: 3 }Static Variable: One copy for all objects
Static Function: Can access only static members
Use for: Counting objects, shared resources
-
Friend Function = Non-member function that can access private members.
class Box { int length; public: Box(int l) : length(l) {} friend int getLength(Box b); // Friend declaration }; // Friend function (not member!) int getLength(Box b) { return b.length; // Can access private }Also: Friend Class
class A { friend class B; // B can access A's private members };Note: Friendship is not inherited, not mutual
-
5 Types of Inheritance:
1. Single: One parent → One child
class A {}; class B : public A {};2. Multiple: Many parents → One child
class C : public A, public B {};3. Multilevel: Chain: A → B → C
4. Hierarchical: One parent → Many children
5. Hybrid: Combination of above
Diamond Problem: Solved using virtual inheritance
class B : virtual public A {}; -
Inheritance Syntax:
class Child : access_specifier Parent { // members };Access Modes:
Base Member public protected private public public protected private protected protected protected private private ✗ ✗ ✗ Example:
class Animal { protected: string name; public: void speak() { cout << "Sound"; } }; class Dog : public Animal { public: void bark() { cout << name << " barks!"; } };
-
Order of Execution:
Base Constructor → Derived ConstructorDestructor Order: Reverse
Derived Destructor → Base DestructorCalling Base Constructor:
class Base { public: Base(int x) { cout << x; } }; class Derived : public Base { public: Derived(int a, int b) : Base(a) { cout << b; } }; Derived d(10, 20); // Output: 10 20Use initializer list to call base constructor!
-
Polymorphism = "Many forms" - same name, different behavior.
2 Types:
1. Compile-time (Static)
- Function Overloading
- Operator Overloading
- Resolved at compile time
2. Runtime (Dynamic)
- Virtual Functions
- Function Overriding
- Resolved at runtime
Example:
// Overloading (compile-time) int add(int a, int b) { return a+b; } float add(float a, float b) { return a+b; } // Overriding (runtime) class Base { virtual void show() {} }; class Derived : public Base { void show() {} };
-
Function Overloading = Same name, different parameters.
class Calculator { public: int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } };Rules:
- Different number of parameters, OR
- Different types of parameters
- Return type alone is NOT enough!
Resolved at: Compile time
-
Operator Overloading = Give new meaning to operators for custom types.
class Complex { int real, imag; public: Complex(int r, int i) : real(r), imag(i) {} // Overload + operator Complex operator+(Complex &c) { return Complex(real + c.real, imag + c.imag); } }; int main() { Complex c1(2, 3), c2(4, 5); Complex c3 = c1 + c2; // Uses overloaded + }Cannot overload: :: . .* ?: sizeof
-
Virtual Function = Function that can be overridden in derived class.
class Animal { public: virtual void speak() { cout << "Animal speaks"; } }; class Dog : public Animal { public: void speak() override { cout << "Dog barks"; } }; int main() { Animal* ptr = new Dog(); ptr->speak(); // Output: Dog barks }Key Points:
- Use
virtualkeyword in base - Use
overridein derived (optional but recommended) - Enables runtime polymorphism
- Uses vtable (virtual table)
- Use
-
Pure Virtual Function = Virtual function with no body.
Abstract Class = Class with at least one pure virtual function.
class Shape { // Abstract class public: virtual void draw() = 0; // Pure virtual virtual float area() = 0; }; class Circle : public Shape { float radius; public: void draw() override { cout << "Drawing circle"; } float area() override { return 3.14 * radius * radius; } };Rules:
- Cannot create objects of abstract class
- Derived class MUST implement all pure virtual functions
- Used for interfaces
-
Exception Handling = Mechanism to handle runtime errors.
Keywords: try, catch, throw
try { int x = 10, y = 0; if (y == 0) throw "Division by zero!"; cout << x/y; } catch (const char* msg) { cout << "Error: " << msg; } catch (...) { cout << "Unknown error"; }Flow:
- 1. Code in
tryblock - 2. If error,
throwexception - 3. Matching
catchhandles it
Standard Exceptions:
exception,runtime_error,logic_error - 1. Code in
-
File Streams:
ifstream- Input (read)ofstream- Output (write)fstream- Both
#include <fstream> // Writing to file ofstream outFile("data.txt"); outFile << "Hello World"; outFile.close(); // Reading from file ifstream inFile("data.txt"); string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close();File Modes:
ios::in,ios::out,ios::app,ios::binaryAlways close files!
-
File Open Modes:
Mode Description ios::inOpen for reading ios::outOpen for writing ios::appAppend at end ios::truncTruncate existing ios::binaryBinary mode ios::ateStart at end Combining modes:
fstream file; file.open("data.txt", ios::in | ios::out); if (!file.is_open()) { cerr << "Failed to open!"; }Functions:
open(),close(),is_open(),eof(),good()
No card matches that search.
1/20
0
0:00
Question
Click the card or press Space to flip
Answer
Diagram for this card
Run complete
0 nailed · 0 in the pile · 0:00 · best combo 0
Scroll to zoom · drag to pan · Esc to close
Shortcuts
- S
- Start the run
- Space
- Show me the answer
- ← →
- Previous / next card
- 1 2
- Not yet / Nailed it
- D
- Open the diagram
- F
- Diagram full screen
- /
- Search the deck
- Esc
- Close whatever is open