Classes
by Eddie HuangA class is to a car factory as an object is to a car. Classes define the behavior of a type of object. They contain variables and functions that are inherent to the class.
A Simple Rectangle Example
rectangle.h
class Rectangle {
int width, height;
public:
Rectangle();
Rectangle(int a, int b);
int area() {
return width * height;
}
int circumference();
};
rectangle.cpp
Rectangle::Rectangle() {
width = 5;
height = 5;
}
Rectangle::Rectangle(int a, int b) {
this->width = a;
this->height = b;
}
int Rectangle::circumference() {
return (width + height) * 2;
}
main.cpp
#include <iostream>
using namespace std;
int main() {
Rectangle rect(3,4);
Rectangle rect_default;
cout << "rect area: " << rect.area() << endl;
cout << "rect_default area: " << rect_default.area() << endl;
return 0;
}
Output
rect area: 12
rect_default area: 25