Master object-oriented programming, file handling, and the STL in C++.
Build real-world applications with OOP, file handling, and dynamic containers.
class BankAccount {
private:
string owner;
double balance;
public:
// Constructor and methods go here
};private: members can only be accessed within the classpublic: members can be accessed from outsideBankAccount(string n, double b) : owner(n), balance(b) {}: owner(n), balance(b) for efficiencystring getOwner() { return owner; }double getBalance() { return balance; }void deposit(double amount) {
if (amount > 0) balance += amount;
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance)
balance -= amount;
}Owner: John Doe
Balance: $1000
After deposit of $500: $1500
After withdrawal of $200: $1300
class Name { private: ... public: ... };ClassName(params) : member(val) {}ClassName obj(args);obj.methodName();Review feedback below
#include <fstream>ofstream - output file stream (write)ifstream - input file stream (read)fstream - both read and writeofstream outFile("data.txt");
if (outFile.is_open()) {
outFile << "Hello, File!" << endl;
outFile << "Line 2" << endl;
outFile.close();
}is_open()<< just like with coutclose() when doneifstream inFile("data.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();getline() reads one line at a timeios::app - append to end of fileios::trunc - clear file before writing (default)ios::binary - binary modeWriting to file...
File written successfully!
Reading from file:
Hello, File!
Line 2
C++ is awesome!
ofstream file("name.txt"); file << data;ifstream file("name.txt"); getline(file, str);if (file.is_open())file.close();ofstream file("name.txt", ios::app);Review feedback below
#include <vector>vector<int> numbers;<>vector<int> nums = {1, 2, 3};numbers.push_back(10);numbers.push_back(20);cout << numbers[0]; // Access by indexcout << numbers.at(0); // Bounds-checked accesscout << numbers.size(); // Number of elementsfor (int num : numbers) {
cout << num << " ";
}pop_back() - remove last elementclear() - remove all elementsempty() - check if emptyfront() / back() - first/last elementVector size: 5
Elements: 10 20 30 40 50
First: 10, Last: 50
After pop_back: 10 20 30 40
Using iterator: 10 20 30 40
vector<type> name;vec.push_back(value);vec.size();for (type item : vec) { ... }vec.pop_back();Review feedback below