cpp / beginner
Snippet
Introduction to Classes and Objects
Classes are blueprints for creating objects in C++. A class groups related data (variables) and functions (methods) together. In this example, we define a Dog class with name and age attributes, plus bark() and birthday() methods. The main() function creates an instance (object) of Dog called myDog and interacts with it using the dot operator.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Dog {public:std::string name;int age;void bark() {std::cout << name << " says: Woof! Woof!" << std::endl;}void birthday() {age++;}};int main() {Dog myDog;myDog.name = "Buddy";myDog.age = 3;myDog.bark();myDog.birthday();return 0;}
Breakdown
1
class Dog {
Declares a new class named Dog starting the class definition
2
public:
Access specifier allowing members to be accessed from outside the class
3
std::string name;
Member variable storing the dog's name
4
int age;
Member variable storing the dog's age
5
void bark() { ... }
Member function that outputs a bark message
6
Dog myDog;
Creates an object (instance) of the Dog class
7
myDog.name = "Buddy";
Accesses and sets the name member using the dot operator