Classes and objects
Constructors, private data and const methods.
C++
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
int balance = 0;
public:
explicit Account(string name) : owner(std::move(name)) {}
void deposit(int amount) {
if (amount > 0) balance += amount;
}
int getBalance() const {
return balance;
}
};
int main() {
Account a("Meena");
a.deposit(500);
a.deposit(-10);
cout << a.getBalance() << "\n";
return 0;
}Output
500
Members are private by default in a class. The colon after the constructor is an initialiser list, and const after a method promises that it will not change the object.