cpp / beginner
Snippet
Your First C++ Class
A class is a blueprint for creating objects. It groups related data (attributes) and functions (methods) together. Here, the Dog class has two attributes (name and age) and one method (bark). Objects are created from classes using the class name followed by the object name. Access class members 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
23
#include <iostream>#include <string>class Dog {public:std::string name;int age;void bark() {std::cout << name << " says: Woof!" << std::endl;}};int main() {Dog myDog;myDog.name = "Buddy";myDog.age = 3;myDog.bark();return 0;}
Breakdown
1
class Dog { ... };
Class definition with curly braces
2
std::string name; int age;
Member attributes to store data
3
void bark() { ... }
Member function that uses class data
4
Dog myDog;
Creates an instance/object of the Dog class
5
myDog.name = "Buddy";
Access and assign values using dot operator