Mastering C++
Class Constructors
Classes In C++In C++ classes a constructor is a special function within a class that runs automatically when you create an object. It sets up the object with initial values, so you don’t have to assign values one by one.
Constructors - A
Let’s add a default constructor to our Person class. This will set up default values for each Person object we create.
class Person {
public:
string name;
int age;
double height;
// Default constructor
Person() {
name = "NO NAME";
age = 0;
height = 0.0;
}
};With this default constructor, every time we create a new Person without setting any values, it will start with these safe defaults. This means that instead of having random or NULL values, each new Person will have "NO NAME" for name, 0 for age, and 0.0 for height.
Let's see an example:
Person p; // Calls the default constructor
cout << p.name << " - " << p.age << " - " << p.height << endl;OUTPUT:
NO NAME - 0 - 0.0Constructors - B
We can also create a constructor that takes parameters to set name, age, and height when we create a Person object. In this case, we’ll use this-> to avoid confusion between the class’s variables and the parameters with the same names.
class Person {
public:
string name;
int age;
double height;
// Parameterized constructor
Person(string name, int age, double height) {
this->name = name; // "this->name" refers to the class variable, "name" refers to the parameter
this->age = age;
this->height = height;
}
};Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.