capypad
0 day streak
cpp / beginner
Snippet

Defining Your First Class

A class is a blueprint for creating objects. It bundles data (variables) and functions (methods) together. The public keyword makes members accessible from outside the class. Objects are instances of a class, created just like normal variables.

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
27
28
#include <iostream>
#include <string>
 
class Dog {
public:
std::string name;
int age;
void bark() {
std::cout << name << " says: Woof! Woof!" << std::endl;
}
void birthday() {
age++;
std::cout << name << " is now " << age << " years old!" << std::endl;
}
};
 
int main() {
Dog myDog;
myDog.name = "Bella";
myDog.age = 3;
myDog.bark();
myDog.birthday();
return 0;
}
Breakdown
1
class Dog {
Defines a new class type called Dog
2
public:
Access modifier: following members can be accessed from outside
3
std::string name;
Data member storing the dog's name
4
void bark()
Member function that makes the dog bark
5
Dog myDog;
Creates an object (instance) of the Dog class