capypad
0 day streak
cpp / beginner
Snippet

Simple Class with Constructor

Classes bundle data (attributes) and functions (methods) into a single unit. This Dog class has a constructor that initializes name and age when creating a Dog object. The bark() method demonstrates how objects encapsulate behavior. You create instances with the constructor, then call their methods using dot notation. Classes are the foundation of object-oriented programming in C++.

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
#include <iostream>
#include <string>
class Dog {
public:
std::string name;
int age;
Dog(std::string n, int a) {
name = n;
age = a;
}
void bark() {
std::cout << name << " says: Woof!" << std::endl;
}
};
 
int main() {
Dog myDog("Buddy", 3);
myDog.bark();
return 0;
}
Breakdown
1
class Dog {
Class definition starting with keyword and class name
2
public:
Access specifier making members accessible from outside the class
3
Dog(std::string n, int a)
Constructor - same name as class, initializes new objects
4
name = n; age = a;
Assignment statements inside constructor body
5
void bark()
Member function declaration returning nothing
6
Dog myDog("Buddy", 3);
Object creation calling the constructor with arguments