capypad
0 day streak
cpp / beginner
Snippet

Class Constructors

Constructors initialize objects when they are created. They have the same name as the class and no return type. The initializer list : name(n), age(a) sets values directly. Multiple objects can be created from the same class.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Dog {
private:
std::string name;
int age;
 
public:
Dog(std::string n, int a) : name(n), age(a) {}
void bark() {
std::cout << name << " says: Woof!" << std::endl;
}
};
 
Dog myDog("Buddy", 3);
myDog.bark();
Breakdown
1
Dog(std::string n, int a) : name(n), age(a)
Constructor with initializer list that sets name and age
2
void bark()
Member function that accesses the private name field
3
Dog myDog("Buddy", 3);
Creates a Dog object with name "Buddy" and age 3