0% found this document useful (0 votes)
10 views34 pages

OOPS Codes

The document covers various C++ programming concepts including operator overloading, data conversion, function overloading, runtime polymorphism, and exception handling. It also discusses file I/O operations, templates, and the Standard Template Library (STL) components. Each section includes code examples to illustrate the concepts effectively.

Uploaded by

Pragati Shirole
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views34 pages

OOPS Codes

The document covers various C++ programming concepts including operator overloading, data conversion, function overloading, runtime polymorphism, and exception handling. It also discusses file I/O operations, templates, and the Standard Template Library (STL) components. Each section includes code examples to illustrate the concepts effectively.

Uploaded by

Pragati Shirole
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

1.

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;
}

2. Data Conversion and Type Casting


a) Implicit Conversion
#include <iostream>
using namespace std;

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 Derived : public Base {


public:
void display() override {
cout << "Derived class display" << endl;
}
};
int main() {
Base *ptr;
Derived d;
ptr = &d;
ptr->display(); // Output: Derived class display
return 0;
}
b) Abstract Base Class and Pure Virtual Function
#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};

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;
}
};

class Derived : public Base {


public:
~Derived() {
cout << "Derived destructor" << endl;
}
};

int main() {
Base *b = new Derived();
delete b; // Correctly calls both destructors
return 0;
}

5. Pitfalls of Operator Overloading


#include <iostream>
using namespace std;

class Number {
int value;

public:
Number(int v) : value(v) {}

// Overloading += for demonstration


Number operator+=(const Number &other) {
value += other.value;
return *this;
}

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.

2. Stream and Files


a) Basic Stream Operations
#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Input and Output Stream Example
string data;

cout << "Enter a string: ";


cin >> data; // Using input stream (cin)
cout << "You entered: " << data << endl; // Using output stream (cout)

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();

ifstream inFile("example.txt"); // Read from file


string data;
while (getline(inFile, data)) {
cout << data << endl; // Output: C++ is fun
}
inFile.close();
return 0;
}

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;
}

5. Disk File I/O with Streams


a) Writing and Reading Numbers
#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Writing to file
ofstream outFile("numbers.txt");
outFile << 5 << " " << 10 << endl;
outFile.close();

// Reading from file


ifstream inFile("numbers.txt");
int a, b;
inFile >> a >> b;
cout << "Read numbers: " << a << " and " << b << endl; // Output: 5 and 10
inFile.close();
return 0;
}

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";

// Move file pointer to beginning


file.seekg(0);
string data;
file >> data;
cout << "Read from file: " << data << endl; // Output: C++

file.close();
return 0;
}

7. File I/O with Member Functions


#include <iostream>
#include <fstream>
using namespace std;

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;
}

8. Overloading Extraction and Insertion Operators


#include <iostream>
#include <fstream>
using namespace std;
class Number {
int value;

public:
Number(int v = 0) : value(v) {}

friend ostream &operator<<(ostream &out, const Number &n) {


out << "Value: " << n.value;
return out;
}

friend istream &operator>>(istream &in, Number &n) {


in >> n.value;
return in;
}
};

int main() {
Number n;
cout << "Enter a number: ";
cin >> n; // Overloaded >>
cout << n << endl; // Overloaded <<
return 0;
}

9. Memory as a Stream Object


#include <iostream>
#include <sstream>
using namespace std;

int main() {
stringstream ss;

// Writing to stringstream
ss << "C++ " << 5;

// Reading from stringstream


string text;
int number;
ss >> text >> number;

cout << "Text: " << text << ", Number: " << number << endl; // Output: Text:
C++, Number: 5
return 0;
}

10. Command-Line Arguments


#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {


cout << "Number of arguments: " << argc << endl;
for (int i = 0; i < argc; i++) {
cout << "Argument " << i << ": " << argv[i] << endl;
}
return 0;
}

11. Printer Output


a) Using \f for Form Feed
#include <iostream>
using namespace std;

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 divide(int a, int b) {


if (b == 0) {
throw runtime_error("Divide by zero error!");
}
return a / b;
}
int main() {
try {
cout << "Result: " << divide(10, 2) << endl; // Valid
cout << "Result: " << divide(10, 0) << endl; // Will throw
} catch (const exception &e) {
cerr << "Caught Exception: " << e.what() << endl;
}
return 0;
}

b) Multiple Catch Blocks


#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;
}

e) Constructor, Destructor, and Exception Handling


#include <iostream>
#include <stdexcept>
using namespace std;

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;
}

f) Exception and Inheritance


#include <iostream>
using namespace std;

class BaseException : public exception {


public:
const char *what() const noexcept override {
return "Base Exception";
}
};

class DerivedException : public BaseException {


public:
const char *what() const noexcept override {
return "Derived Exception";
}
};

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;

template <typename T>


T add(T a, T b) {
return a + b;
}
int main() {
cout << "Int: " << add(5, 10) << endl; // Output: 15
cout << "Double: " << add(3.5, 2.5) << endl; // Output: 6
return 0;
}

b) Overloading Function Templates


#include <iostream>
using namespace std;

template <typename T>


T add(T a, T b) {
return a + b;
}

template <typename T>


T add(T a, T b, T c) {
return a + b + c;
}

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;

template <typename T>


class Box {
T value;

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;
}

d) Class Template with Non-Type Parameters


#include <iostream>
using namespace std;
template <typename T, int size>
class Array {
T arr[size];

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;
}

e) Template and Friend Functions


#include <iostream>
using namespace std;
template <typename T>
class Box {
T value;

public:
Box(T v) : value(v) {}

friend void display(const Box &b) {


cout << "Box value: " << b.value << endl;
}
};

int main() {
Box<int> intBox(10);
display(intBox); // Output: Box value: 10

Box<string> strBox("C++");
display(strBox); // Output: Box value: C++
return 0;
}

f) typename and export Keywords


Using typename
#include <iostream>
using namespace std;

template <typename T>


class Container {
public:
typename T::value_type getValue(const T &container) {
return container[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;

// Set Operations (Union)


set<int> set1 = {1, 2, 3}, set2 = {3, 4, 5};
set<int> result;
set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(result,
result.begin()));
cout << "Set Union: ";
for (int n : result) {
cout << n << " ";
}

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};

// Input and Output Iterators


cout << "Using Input Iterator: ";
for (auto it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
cout << endl;

// 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;
}

3. Object-Oriented Programming – Roadmap to the Future


Future Trends in Object-Oriented Programming:
1. Functional Programming Integration:
o Modern languages like Python, Java, and C++ are blending OOP
with functional programming paradigms for cleaner, more efficient
code.
2. Multi-Paradigm Programming:
o Languages like C++ and Rust allow for procedural, functional, and
object-oriented programming, providing flexibility.
3. Advanced Metaprogramming:
o Metaprogramming and templates are becoming more sophisticated,
making C++ ideal for high-performance applications.
4. AI and Machine Learning Integration:
o OOP principles are vital for designing scalable and modular AI
systems.
5. Cloud and Distributed Systems:
o OOP concepts like encapsulation and inheritance help design
robust, scalable microservices.
6. Enhanced Memory Management:
o Modern languages and frameworks focus on automatic memory
management, making it easier to build efficient applications.
7. Secure Programming Practices:
o Focus on secure coding (e.g., C++’s std::unique_ptr and
std::shared_ptr for safe memory handling).

You might also like