capypad
0 day streak
cpp / beginner
Snippet

Your First Class: Introduction to OOP

Classes are blueprints for creating objects. A class defines properties (like name and age) and behaviors (like bark and birthday). You create an object from a class using the class name as a type. Each object has its own copy of the properties.

snippet.cpp
cpp
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
#include <iostream>
using namespace std;
 
class Dog {
public:
string name;
int age;
void bark() {
cout << name << " says: Woof!" << endl;
}
void birthday() {
age = age + 1;
}
};
 
int main() {
Dog myDog;
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();
myDog.birthday();
cout << myDog.name << " is now " << myDog.age << " years old" << endl;
return 0;
}
Breakdown
1
class Dog {
Defines a new class type called Dog
2
string name; int age;
Member variables storing the dog's data
3
void bark()
Member function that performs an action
4
Dog myDog;
Creates an actual Dog object instance
5
myDog.name = "Buddy";
Accesses and sets the object's name property