capypad
0 day streak
cpp / beginner
Snippet

Constructors and Initialization

A constructor is a special method called automatically when an object is created. It initializes the object's data. Private members can only be accessed by the class itself, protecting internal data from outside interference.

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 Car {
private:
std::string brand;
int speed;
public:
Car(std::string b, int s) {
brand = b;
speed = s;
}
void showInfo() {
std::cout << brand << " - Speed: " << speed << " km/h" << std::endl;
}
};
 
int main() {
Car car1("BMW", 200);
Car car2("Mercedes", 180);
car1.showInfo();
car2.showInfo();
return 0;
}
Breakdown
1
Car(std::string b, int s) {
Constructor with parameters to initialize the Car object
2
brand = b;
Assigns parameter value to the member variable
3
private:
Access modifier that restricts access to class members only
4
Car car1("BMW", 200);
Creates car1 using the constructor with two arguments