What is an object? | ||
component of a program | ||
contains variables and data | ||
perform certain actions | ||
interact with other pieces of the program | ||
What is a class? | ||
blue prints of objects | ||
abstraction data type (ADT) | ||
Instance – every object is an instance of a class | ||
a real thing of a class | ||
can be manipulated | ||
instances keep track of their own information | ||
called member data/variables | ||
knows how to do things with different methods | ||
Method (interface) | ||||
member variable except it can do more tricks | ||||
like move(), attackMonster() and etc.. | ||||
Special methods | ||||
Constructors | ||||
get the object ready to be used | ||||
Destructors | ||||
terminate the object | ||||
struct Player{ | |
int health; | |
int strength; | |
int agility; | |
} | |
Player Jane, John; | |
class Player { | |
public: | |
int health; | |
int strength; | |
int agility; | |
}; | |
Player Jane, John; |
Player:: Player () { | ||
strength = 10; | ||
agility = 10; | ||
health = 10; | ||
} | ||
Player::~Player() { | ||
strength = 0; | ||
agility = 0; | ||
health = 0; | ||
} //automatically called | ||
Purpose | |||
set up an object: i.e. instantiate an object. | |||
How | |||
Constructor automatically invoked at declaration time | |||
Player John; //default constructor | |||
Player::Player(int s, int a) { | |||
strength = stg; | |||
agility = agl; | |||
health = 10; | |||
} | |||
Player Jane(20, 5); //function overloading |
class Player { | |
int health; | |
int strength; | |
int agility; | |
Player(); // constructor - no return type | |
Player(int s, int a); // alternate constructor void void move(); | |
void attackMonster(); | |
void getTreasure(); | |
}; |
class Player { | |
private: // hidden | |
int health; | |
int strength; | |
int agility; | |
public: | |
Player(); // constructor - no return type | |
Player(int s, int a); // alternate constructor void void move(); | |
void attackMonster(); | |
void getTreasure(); | |
}; |
void Player::move() { | |
cout <<“I’ve moved to a new position.” << endl; | |
} | |
void Player::getTreasure() { | |
health++; // increments health by one | |
} | |
int main() { | |
Player Jane, John(5, 5); | |
cout <<“Jane’s health:.” << Jane.health << endl; | |
Jane.getTreasure(); | |
cout <<“Jane’s health:.” << Jane.health << endl; | |
}; |
class Engine { | |
public: | |
void start() const {} | |
void rev() const {} | |
void stop() const {} | |
}; | |
class Wheel { | |
public: | |
void inflate(int psi) const {} | |
}; | |
class Window { | |
public: | |
void rollup() const {} | |
void rolldown() const {} | |
}; | |
class Door { | |
public: | |
Window window; | |
void open() const {} | |
void close() const {} | |
}; |
class Car { | |
public: | |
Engine engine; | |
Wheel wheel[4]; | |
Door left, right; // 2-door | |
}; | |
int main() { | |
Car car; | |
car.left.window.rollup(); | |
car.wheel[0].inflate(72); | |
} |