capypad
0 day streak
cpp / beginner
Snippet

Constructors: Initializing Objects Properly

A constructor is a special function that runs automatically when an object is created. It sets up the initial state of the object. Here, the Student constructor takes two parameters (name and grade) and assigns them to the object's attributes. This ensures every Student object starts with valid data instead of random values.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Student {
public:
string name;
int grade;
Student(string n, int g) {
name = n;
grade = g;
}
void display() {
cout << name << " has grade: " << grade << endl;
}
};
 
int main() {
Student s1("Anna", 95);
s1.display();
return 0;
}
Breakdown
1
Student(string n, int g) {
Constructor with same name as the class, takes name and grade
2
name = n;
Assigns parameter n to the member variable name
3
Student s1("Anna", 95);
Creates student object with initial values right away
4
void display()
Member function to show student information