RUN

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.

main.cpp

#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

Open the full C++ online compiler →