PF And OOP Notes
PF And OOP Notes
Notebook
Juniors
int main() {
cout << "Hello, World!";
return 0;
}
using namespace std; : Avoids prefixing std:: for standard functions like cout .
Python:
print("Hello, World!")
Data Types
Programming Fundamentals 1
C++:
Python:
age = 25 # Integer
price = 19.99 # Float
grade = 'A' # Single character (also treated as a str
ing)
is_student = True # Boolean (True/False)
Python automatically determines the data type based on the value assigned.
Control Statements
C++:
Programming Fundamentals 2
else : Executes if the condition is false.
Python:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Syntax
switch(expression) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
// More cases...
default:
// Code block for unmatched cases
}
Explanation of Syntax
switch(expression) : The expression is evaluated, and its result is compared with
each case value.
Programming Fundamentals 3
: Represents a possible match for the expression . If the
case value: expression
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Enter a number (1-3): ";
cin >> choice;
switch(choice) {
case 1:
cout << "You selected option 1.\n";
break;
case 2:
cout << "You selected option 2.\n";
break;
case 3:
cout << "You selected option 3.\n";
break;
default:
cout << "Invalid choice.\n";
}
return 0;
}
Output
Programming Fundamentals 4
1. If choice = 1 :
Output:
You selected option 1.
2. If choice = 4 :
Output:
Invalid choice.
Key Points
1. Expression Type:
Floating-point ( float , double ) and string values are not allowed as switch
expressions.
2. Fall-through Behavior:
Example:
int x = 2;
switch(x) {
case 1:
cout << "One\n";
case 2:
cout << "Two\n";
case 3:
cout << "Three\n";
}
// Output: Two
// Three
3. Default Case:
The default case is optional but ensures that all unmatched conditions are
handled.
Programming Fundamentals 5
It acts like the else block in an if-else structure.
#include <iostream>
using namespace std;
int main() {
char grade;
cout << "Enter your grade (A, B, C): ";
cin >> grade;
switch(grade) {
case 'A':
cout << "Excellent!\n";
break;
case 'B':
cout << "Good job!\n";
break;
case 'C':
cout << "You passed.\n";
break;
default:
cout << "Invalid grade.\n";
}
return 0;
}
Output
1. If grade = 'A' :
Output:
Excellent!
Programming Fundamentals 6
2. If grade = 'D' :
Output:
Invalid grade.
Advantages of Switch
Clear and concise for multiple discrete conditions.
Limitations
Only works with integral or enumerated types.
Cannot handle ranges or complex conditions (use if-else for such scenarios).
Using if-elif :
if choice == 1:
print("You selected option 1.")
elif choice == 2:
print("You selected option 2.")
elif choice == 3:
print("You selected option 3.")
else:
print("Invalid choice.")
Using a Dictionary:
Programming Fundamentals 7
def option1():
return "You selected option 1."
def option2():
return "You selected option 2."
def option3():
return "You selected option 3."
By mastering the switch statement in C++, you can efficiently handle multi-way
branching in programs, making them more structured and easier to debug.
Loops
C++:
i = 0 : Initialization.
Python:
for i in range(5):
Programming Fundamentals 8
print("Number:", i) # Outputs numbers 0 to 4
Functions
C++:
#include <iostream>
using namespace std;
int main() {
cout << add(5, 3);
return 0;
}
Python:
print(add(5, 3))
Programming Fundamentals 9
C++ Arrays:
Python Lists:
Lists in Python are more flexible and can hold different data types.
Strings
C++:
#include <iostream>
#include <string>
using namespace std;
Python:
Programming Fundamentals 10
name = "Alice" # Declares a string
print(len(name)) # Outputs the length of the string
(5)
Strings in Python are treated as objects, and many operations are built-in.
File Handling
C++:
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt"); // Opens a file for writing
file << "Hello, World!"; // Writes to the file
file.close(); // Closes the file
return 0;
}
Python:
Error Handling
Error Handling in C++
C++ uses try , catch , and throw to handle exceptions.
Programming Fundamentals 11
Exceptions are events that disrupt the normal flow of the program (e.g.,
division by zero, invalid memory access).
Syntax
try {
// Code that might throw an error
throw exception; // Throw an error (exception)
} catch (type e) {
// Code to handle the error
}
Example
#include <iostream>
using namespace std;
int main() {
try {
int a = 5, b = 0;
if (b == 0)
throw "Division by zero error!"; // Throw an exc
eption
cout << a / b; // This line won't execute
} catch (const char* e) {
// Handle the exception
cout << "Error: " << e << endl;
}
return 0;
}
Explanation:
1. try Block: The code that might cause an error is placed here.
Programming Fundamentals 12
2. throw Statement: Used to raise (or "throw") an exception. In this case, it's a
string message.
3. catch Block: Handles the exception. Here, it catches the thrown string and
displays the error message.
Syntax
try:
# Code that might raise an error
except ExceptionType:
# Code to handle the error
else:
# Code to execute if no error occurs
finally:
# Code that always executes
Example
try:
a = 5
b = 0
result = a / b # This line will raise an exception
except ZeroDivisionError as e:
# Handle the exception
print("Error:", e)
else:
# Executes if no exception occurs
print("Result:", result)
finally:
Programming Fundamentals 13
# Always executes
print("Execution complete.")
Explanation:
1. try Block: The risky code is placed here (e.g., division by zero).
5. Do Not Abuse Exceptions: Use exceptions for unexpected situations, not for
normal control flow.
Key Differences
Programming Fundamentals 14
Pointers in Object-Oriented Programming
(OOP)
Definition:
Pointers are variables that store the memory address of another variable. They are
widely used in C++ for dynamic memory allocation, object management, and
implementing advanced OOP features like polymorphism.
int a = 10;
int* p = &a; // p stores the address of a
int a = 10;
int* p = &a;
cout << *p; // Outputs 10
5. Pointers to Objects:
Programming Fundamentals 15
class Sample {
public:
int x;
Sample(int val) : x(val) {}
};
Example in C++:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
void displayDetails() {
cout << "Brand: " << brand << ", Year: " << year << e
ndl;
}
};
Programming Fundamentals 16
int main() {
Car car1;
car1.brand = "Toyota";
car1.year = 2020;
Example in Python:
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def display_details(self):
print(f"Brand: {self.brand}, Year: {self.year}")
In Python, it is __init__ .
Programming Fundamentals 17
In C++, it is prefixed with ~ .
In Python, it is __del__ .
Example in C++:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
// Constructor
Car(string b, int y) {
brand = b;
year = y;
cout << "Car object created!" << endl;
}
// Destructor
~Car() {
cout << "Car object destroyed!" << endl;
}
void displayDetails() {
cout << "Brand: " << brand << ", Year: " << year << e
ndl;
}
};
int main() {
Car car1("Toyota", 2020);
car1.displayDetails();
Programming Fundamentals 18
return 0;
}
Example in Python:
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
print("Car object created!")
def __del__(self):
print("Car object destroyed!")
def display_details(self):
print(f"Brand: {self.brand}, Year: {self.year}")
Friend Functions
Definition:
A friend function in C++ can access the private and protected members of a
class even though it is not a member of that class.
Not applicable in Python since it uses dynamic attribute access, and there is
no strict privacy enforcement.
Example in C++:
#include <iostream>
using namespace std;
Programming Fundamentals 19
class Box {
private:
int width;
public:
Box(int w) : width(w) {}
int main() {
Box b1(50);
displayWidth(b1); // Outputs: Width: 50
return 0;
}
Operator Overloading
Definition:
Operator overloading allows operators to be redefined for user-defined types.
Example in C++:
#include <iostream>
using namespace std;
class Complex {
Programming Fundamentals 20
private:
int real, imag;
public:
Complex(int r, int i) : real(r), imag(i) {}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Using overloaded '+' operator
c3.display(); // Outputs: 4 + 6i
return 0;
}
Example in Python:
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
Programming Fundamentals 21
def __str__(self):
return f"{self.real} + {self.imag}i"
c1 = Complex(3, 4)
c2 = Complex(1, 2)
c3 = c1 + c2 # Using overloaded '+' operator
print(c3) # Outputs: 4 + 6i
1. Encapsulation
Encapsulation is the bundling of data (variables) and methods (functions) that
operate on the data into a single unit, typically a class. It ensures that the internal
details of the class are hidden from the outside world.
Example:
cpp
Copy code
class BankAccount {
private:
double balance;
public:
BankAccount(double initialBalance) : balance(initialBalan
ce) {}
Programming Fundamentals 22
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
int main() {
BankAccount account(100.0);
account.deposit(50.0);
cout << "Balance: $" << account.getBalance() << endl;
return 0;
}
2. Inheritance
Inheritance allows one class (derived class) to inherit properties and methods
from another class (base class). It promotes code reusability.
Example:
cpp
Copy code
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
Programming Fundamentals 23
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};
int main() {
Dog myDog;
myDog.eat();
myDog.bark();
return 0;
}
3. Polymorphism
Polymorphism allows objects to take many forms. It enables a single interface to
control access to a variety of types.
Example:
Compile-Time Polymorphism (Function Overloading):
cpp
Copy code
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
Programming Fundamentals 24
int main() {
Calculator calc;
cout << calc.add(2, 3) << endl; // Outputs 5
cout << calc.add(2.5, 3.5) << endl; // Outputs 6.0
return 0;
}
cpp
Copy code
class Animal {
public:
virtual void sound() {
cout << "This is an animal sound." << endl;
}
};
int main() {
Animal* animal = new Dog();
animal->sound(); // Outputs "The dog barks."
delete animal;
return 0;
}
Programming Fundamentals 25
4. Abstraction
Abstraction hides implementation details and shows only essential features. In
C++, it can be implemented using abstract classes or interfaces.
Example:
cpp
Copy code
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
int main() {
Shape* shape = new Circle();
shape->draw(); // Outputs "Drawing a Circle."
delete shape;
return 0;
}
Programming Fundamentals 26