OOPS Codes
OOPS Codes
Operator Overloading
a) Overloading Unary Operator (-)
#include <iostream>
using namespace std;
class Number {
int value;
public:
Number(int v) : value(v) {}
void operator-() {
value = -value;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number num(5);
-num; // Unary minus
num.display(); // Output: Value: -5
return 0;
}
b) Overloading Binary Operator (+)
#include <iostream>
using namespace std;
class Number {
int value;
public:
Number(int v) : value(v) {}
Number operator+(const Number &other) {
return Number(value + other.value);
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number num1(5), num2(10);
Number sum = num1 + num2; // Binary addition
sum.display(); // Output: Value: 15
return 0;
}
class Number {
int value;
public:
Number(int v) : value(v) {}
operator int() { // Implicit conversion to int
return value;
}
};
int main() {
Number num(5);
int x = num; // Implicit conversion
cout << "Converted Value: " << x << endl; // Output: Converted Value: 5
return 0;
}
b) Explicit Conversion (explicit keyword)
#include <iostream>
using namespace std;
class Number {
int value;
public:
explicit Number(int v) : value(v) {}
int getValue() const {
return value;
}
};
int main() {
Number num(5);
// int x = num; // Error: explicit conversion required
int x = static_cast<int>(num.getValue()); // Explicit conversion
cout << "Converted Value: " << x << endl; // Output: Converted Value: 5
return 0;
}
3. Function Overloading
#include <iostream>
using namespace std;
class Printer {
public:
void print(int x) {
cout << "Integer: " << x << endl;
}
void print(string str) {
cout << "String: " << str << endl;
}
void print(double d) {
cout << "Double: " << d << endl;
}
};
int main() {
Printer p;
p.print(5);
p.print("C++");
p.print(3.14);
return 0;
}
4. Runtime Polymorphism
a) Virtual Functions
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout << "Base class display" << endl;
}
};
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
int main() {
Shape *shape = new Circle();
shape->draw(); // Output: Drawing Circle
delete shape;
return 0;
}
c) Virtual Destructor
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {
cout << "Base destructor" << endl;
}
};
int main() {
Base *b = new Derived();
delete b; // Correctly calls both destructors
return 0;
}
class Number {
int value;
public:
Number(int v) : value(v) {}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number num1(5), num2(10);
num1 += num2; // Works fine
// num1 = num1 + 10; // Error: No matching operator for `+` with int
num1.display(); // Output: Value: 15
return 0;
}
1. Data Hierarchy (Concept)
Data in a program is typically organized in a hierarchy, such as:
Bits → Bytes → Fields → Records → Files → Databases.
int main() {
// Input and Output Stream Example
string data;
return 0;
}
3. Stream Classes
a) ifstream, ofstream, fstream
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt"); // Write to file
outFile << "C++ is fun" << endl; // Writing to the file
outFile.close();
4. Stream Errors
a) Checking for Stream Errors
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("nonexistent.txt");
if (!file) {
cerr << "Error: File does not exist!" << endl;
return 1;
}
string data;
file >> data;
cout << data << endl;
return 0;
}
int main() {
// Writing to file
ofstream outFile("numbers.txt");
outFile << 5 << " " << 10 << endl;
outFile.close();
6. File Pointers
a) Manipulating File Pointers
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out | ios::trunc);
file << "C++ is fun";
file.close();
return 0;
}
class FileHandler {
fstream file;
public:
void writeData(const string &data) {
file.open("member.txt", ios::out);
file << data;
file.close();
}
void readData() {
file.open("member.txt", ios::in);
string data;
file >> data;
cout << "File content: " << data << endl;
file.close();
}
};
int main() {
FileHandler fh;
fh.writeData("C++ is fun");
fh.readData();
return 0;
}
public:
Number(int v = 0) : value(v) {}
int main() {
Number n;
cout << "Enter a number: ";
cin >> n; // Overloaded >>
cout << n << endl; // Overloaded <<
return 0;
}
int main() {
stringstream ss;
// Writing to stringstream
ss << "C++ " << 5;
cout << "Text: " << text << ", Number: " << number << endl; // Output: Text:
C++, Number: 5
return 0;
}
int main() {
cout << "Page 1 content\f"; // Simulates page break
cout << "Page 2 content" << endl;
return 0;
}
1. Exception Handling
a) Fundamentals: Simple Exception Handling
Example: Divide by Zero
#include <iostream>
using namespace std;
int main() {
try {
throw 5; // Can be any type
} catch (int e) {
cout << "Caught an integer: " << e << endl;
} catch (const char *e) {
cout << "Caught a string: " << e << endl;
} catch (...) {
cout << "Caught an unknown exception." << endl;
}
return 0;
}
c) Rethrowing Exceptions
#include <iostream>
using namespace std;
void test() {
try {
throw runtime_error("Initial Exception");
} catch (...) {
cout << "Caught in test(), rethrowing..." << endl;
throw; // Rethrowing the exception
}
}
int main() {
try {
test();
} catch (const exception &e) {
cerr << "Caught in main: " << e.what() << endl;
}
return 0;
}
d) User-Defined Exceptions
#include <iostream>
#include <stdexcept>
using namespace std;
class MyException : public exception {
string message;
public:
MyException(const string &msg) : message(msg) {}
const char *what() const noexcept override {
return message.c_str();
}
};
int main() {
try {
throw MyException("This is a user-defined exception");
} catch (const MyException &e) {
cerr << "Caught: " << e.what() << endl;
}
return 0;
}
class MyClass {
public:
MyClass() {
cout << "Constructor called." << endl;
throw runtime_error("Exception in constructor");
}
~MyClass() {
cout << "Destructor called." << endl;
}
};
int main() {
try {
MyClass obj;
} catch (const exception &e) {
cerr << "Caught Exception: " << e.what() << endl;
}
return 0;
}
int main() {
try {
throw DerivedException();
} catch (const BaseException &e) {
cout << "Caught: " << e.what() << endl; // Will catch derived exception
}
return 0;
}
2. Templates
a) Function Template
#include <iostream>
using namespace std;
int main() {
cout << "Two ints: " << add(5, 10) << endl; // Output: 15
cout << "Three ints: " << add(1, 2, 3) << endl; // Output: 6
return 0;
}
c) Class Template
#include <iostream>
using namespace std;
public:
Box(T v) : value(v) {}
T getValue() {
return value;
}
};
int main() {
Box<int> intBox(10);
Box<string> strBox("C++");
cout << "Int Box: " << intBox.getValue() << endl; // Output: 10
cout << "String Box: " << strBox.getValue() << endl; // Output: C++
return 0;
}
public:
void set(int index, T value) {
if (index >= 0 && index < size) {
arr[index] = value;
}
}
T get(int index) {
return arr[index];
}
};
int main() {
Array<int, 5> intArray;
intArray.set(0, 42);
cout << "Value at index 0: " << intArray.get(0) << endl; // Output: 42
return 0;
}
public:
Box(T v) : value(v) {}
int main() {
Box<int> intBox(10);
display(intBox); // Output: Box value: 10
Box<string> strBox("C++");
display(strBox); // Output: Box value: C++
return 0;
}
int main() {
vector<int> vec = {1, 2, 3};
Container<vector<int>> c;
cout << "First value: " << c.getValue(vec) << endl; // Output: 1
return 0;
}
1. Introduction to STL
The Standard Template Library (STL) is a powerful library in C++ that
provides ready-to-use generic classes and functions for common programming
tasks. It is broadly categorized into:
• Containers: Store data (e.g., vector, list, map).
• Algorithms: Perform operations on data (e.g., sort, find).
• Iterators: Access container elements (e.g., input/output iterators).
2. STL Components
a) Containers
i) Sequence Containers: vector, list, deque
#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main() {
// Vector Example
vector<int> vec = {10, 20, 30};
vec.push_back(40);
for (int val : vec) {
cout << "Vector Element: " << val << endl;
}
// List Example
list<string> myList = {"C++", "is", "fun"};
myList.push_back("!");
for (const string &str : myList) {
cout << "List Element: " << str << endl;
}
return 0;
}
ii) Associative Containers: map, set
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main() {
// Map Example
map<int, string> myMap = {{1, "One"}, {2, "Two"}};
myMap[3] = "Three";
for (auto &pair : myMap) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
// Set Example
set<int> mySet = {10, 20, 20, 30}; // Duplicates removed
mySet.insert(40);
for (int val : mySet) {
cout << "Set Element: " << val << endl;
}
return 0;
}
iii) Container Adapters: stack, queue, priority_queue
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main() {
// Stack Example
stack<int> myStack;
myStack.push(10);
myStack.push(20);
while (!myStack.empty()) {
cout << "Stack Top: " << myStack.top() << endl;
myStack.pop();
}
// Queue Example
queue<int> myQueue;
myQueue.push(100);
myQueue.push(200);
while (!myQueue.empty()) {
cout << "Queue Front: " << myQueue.front() << endl;
myQueue.pop();
}
return 0;
}
b) Algorithms
i) Basic Searching and Sorting
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {30, 10, 20, 40};
// Sorting
sort(nums.begin(), nums.end());
cout << "Sorted Vector: ";
for (int n : nums) {
cout << n << " ";
}
cout << endl;
// Searching
if (binary_search(nums.begin(), nums.end(), 20)) {
cout << "20 found in vector" << endl;
} else {
cout << "20 not found" << endl;
}
return 0;
}
ii) Min-Max and Set Operations
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
int main() {
vector<int> nums = {5, 10, 15, 20};
// Min-Max
cout << "Min: " << *min_element(nums.begin(), nums.end()) << endl;
cout << "Max: " << *max_element(nums.begin(), nums.end()) << endl;
return 0;
}
iii) Heap Sort
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {10, 20, 5, 15};
// Make a heap
make_heap(nums.begin(), nums.end());
cout << "Max heap root: " << nums.front() << endl;
// Heap sort
sort_heap(nums.begin(), nums.end());
cout << "Heap-sorted elements: ";
for (int n : nums) {
cout << n << " ";
}
return 0;
}
c) Iterators
i) Types of Iterators
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
// Reverse Iterator
cout << "Using Reverse Iterator: ";
for (auto it = nums.rbegin(); it != nums.rend(); ++it) {
cout << *it << " ";
}
cout << endl;
// Random Access
cout << "Random Access: " << nums[2] << endl;
return 0;
}