An object is a collection of related variables and methods.
Objects exist at runtime in the computer's memory.
We can refer to the members of an object by qualifying their names with the object's name:
myAccount.balance
myAccount.deposit(3.14);
The second line is an example of a method invocation. We can think of method invocation as a request for an object to execute one of its methods. In this case we are asking an object named myAccount to execute a method named deposit with input 3.14. Presumably, this will increment myAccount.balance by $3.14.
A class is a collection of related variable and method declarations:
class Account {
private double balance = 0;
public double getBalance() {
return this.balance;
}
public void deposit(double amt) {
this.balance += amt;
}
public void withdraw(double amt) {
this.balance -= amt;
}
// etc.
}
Implicit argument:
this = reference to the object executing the method
The members of a class can have private (class), package, protected (package + subclass), or public (program) scope.
Here's the UML notation for a class:
A class can be thought of as a template for creating objects:
Account myAccount = new Account();
Terminology: myAccount is an instance of or instantiates the Account class.
Here is the UML icon representing the myAccount object:
A C++ variable may hold an object, an explicit pointer to an object, or an implicit pointer to an object (called a reference):
Account a, *b = new Account(), &c = a;
Here is the notation for invoking a method:
a.deposit(50);
b->deposit(25); // shorthand for (*b).deposit(50);
c.withdraw(10);
Here is the C++ notation for declaring a class:
// file: Account.h
class Account {
private:
double balance;
public:
Account() { balance = 0; }
double getBalance() {
return this->balance;
}
void deposit(double amt);
void withdraw(double amt);
// etc.
};
Note the constructor. This is necessary because inline initialization of fields is not allowed in C++ and by default fields are initialized to random values.
C++ method implementations can be declared inline (like getBalance) or declared in a separate implementation file:
// file: Account.cpp
#include "Account.h"
void Account::deposit(double amt)
{
this->balance += amt;
}
void Account::withdraw(double amt) {
this->balance -= amt;
}