-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_anatomy.cpp
More file actions
32 lines (28 loc) · 957 Bytes
/
Copy pathclass_anatomy.cpp
File metadata and controls
32 lines (28 loc) · 957 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
class Car {
private: // ---access control (encapsulation)---
int speed; //member variable
std::string model; //each object gets its win copy of these
public:
//-----CONSTRUCTOR: runs auto when an object is created
Car(std::string m, int s) : model(m), speed(s) {
} //initializer list
//----DESTRUCTOR: runs auto when the object is destroyed
~Car() {
//cleanup goes here (free resources)
}
//-----Member functions (a.k.a methods): the object's behaviour----
void accelerate(int amount) {
speed += amount;
}
int getSpeed() const { //const member function: does not modify the object
return speed;
}
};
int main() {
Car myCar("Toyota", 0);
myCar.accelerate(50); //call a methodvia the dot operator
std::cout << "Current speed: " << myCar.getSpeed() << std::endl;
//when myCar goes out of scope at end of main, ~Car runs auto.
return 0;
}