Classes and objects in C++
A class with a constructor, private data and member functions. Press Run to try it, then change the code and run it again.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
string owner;
double balance;
public:
BankAccount(string owner, double balance) : owner(owner), balance(balance) {}
void deposit(double amount) { balance += amount; }
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
void print() const { cout << owner << " has Rs. " << balance << '\n'; }
};
int main() {
BankAccount acc("Asha", 1000);
acc.deposit(500);
if (!acc.withdraw(2000)) cout << "Not enough money\n";
acc.withdraw(300);
acc.print();
}
Output
Press Run to see the output.
More C++ examples
- Hello, World · The classic first C++ program.
- Vectors and sort · Read numbers into a vector, sort them and find the largest.
- Count words with a map · Use std::map to count how often each word appears.
- Binary search · Find a value in a sorted array in O(log n) steps.
- Competitive programming template · Fast input and output with bits/stdc++.h, ready for contest problems.