capypad
0 day streak
cpp / beginner
Snippet

Classes and Objects: Building Blueprints

A class is a blueprint for creating objects. Think of it as a cookie cutter - the class defines the shape, and each object is an actual cookie made from that cutter. In this example, Dog is a class with properties (name, age) and behaviors (bark()). We create an object myDog from this blueprint and can access its members using the dot operator.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Dog {
public:
string name;
int age;
void bark() {
cout << name << " says: Woof!" << endl;
}
};
 
int main() {
Dog myDog;
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();
return 0;
}
Breakdown
1
class Dog {
Keyword to define a new class named Dog
2
public:
Access modifier allowing members to be accessed from outside the class
3
string name;
Member variable to store the dog's name
4
void bark() {
Member function that outputs a bark sound
5
Dog myDog;
Creates an object (instance) of the Dog class
6
myDog.name = "Buddy";
Assigns a value to the object's name property