C++ NOTES: OBJECT-ORIENTED CONCEPTS AND FILE HANDLING
------------------------------------------------------------
1. POLYMORPHISM
Polymorphism means "many forms". In C++, it allows objects to behave differently based on their
types.
Types:
- Compile-time polymorphism (Function Overloading, Operator Overloading)
- Run-time polymorphism (Virtual Functions)
------------------------------------------------------------
2. FUNCTION OVERLOADING
Function Overloading means defining multiple functions with the same name but different
parameters.
Example:
void show();
void show(int);
void show(double, int);
------------------------------------------------------------
3. VIRTUAL FUNCTION
A virtual function is a function in a base class that can be overridden in a derived class using the
'virtual' keyword.
Example:
class Base {
public:
virtual void display() { cout << "Base"; }
};
class Derived : public Base {
public:
void display() override { cout << "Derived"; }
};
------------------------------------------------------------
4. ABSTRACT CLASS
An abstract class contains at least one pure virtual function and cannot be instantiated.
Example:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
------------------------------------------------------------
5. EXCEPTION HANDLING - INTRODUCTION
Exception handling is used to manage runtime errors gracefully using try, throw, and catch blocks.
------------------------------------------------------------
6. TRY-CATCH BLOCK
Structure to detect and handle exceptions:
try {
// code that might throw
} catch (exception_type e) {
// handler code
------------------------------------------------------------
7. EXCEPTION PROPAGATION
If an exception is not caught in the current function, it propagates back to the calling function.
Example:
void A() { throw "Error"; }
void B() { A(); }
main() {
try { B(); }
catch (const char* msg) { cout << msg; }
------------------------------------------------------------
8. FILE INPUT AND OUTPUT OPERATIONS
Header Required: #include <fstream>
Classes:
- ifstream: read from file
- ofstream: write to file
- fstream: read and write
Writing Example:
ofstream out("file.txt");
out << "Hello!";
out.close();
Reading Example:
ifstream in("file.txt");
string line;
while (getline(in, line)) { cout << line; }
in.close();
Modes:
ios::in, ios::out, ios::app, ios::ate, ios::trunc, ios::binary
------------------------------------------------------------
END OF NOTES