Basic knowledge
Detailed explanation of C++ constructor functions
In C++, there is a special member function, which has the same name as the class name, has no return value, does not need to be explicitly called by the user (and cannot be called by the user), but is executed automatically when the object is created. This special member function is the constructor (Constructor).
In the section "Access Rights of C++ Class Members and Class Encapsulation", we assign values to member variables name, age, and score through member functions setname(), setage(), and setscore() respectively. Although this is effective, it seems A bit of a hassle. With the constructor, we can simplify this work by assigning values to member variables while creating the object, see the code below (Example 1):
#include <iostream>
using namespace std;
class Student{
private:
char *m_name;
int m_age;
float m_score;
public:
//declare the constructor
Student(char *name, int age, float score);
//declare normal member function
void show();
};
//define the constructor
Student::Student(char *name, int age, float score){
m_name = name;
m_age = age;
m_score = score;
}
//Define common member function
void Student::show(){
The age of cout<<m_name<<" is "<<m_age<<", and the grade is "<<m_score<<endl;
}
int main(){
// Pass parameters to the constructor when creating an object
Student stu("Xiao Ming", 15, 92.5f);
stu.show();
// Pass parameters to the constructor when creating an object
Student *pstu = new Student("Li Hua", 16, 96);
pstu -> show();
return 0;
}
operation result:
Xiao Ming's age is 15 and his grade is 92.5
Li Hua's age is 16 and his grades are 96
This example defines a constructor Student(char *, int, float) in the Student class, and its role is to assign values to the member variables of the three private properties. To call the constructor, you must pass arguments while creating the object, and the arguments are surrounded by ( ), very similar to a normal function call.
When creating an object on the stack, the actual parameter is after the object name, such as Student stu("Xiao Ming", 15, 92.5f); when creating an object on the heap, the actual parameter is after the class name, such as new Student("Li Hua" , 16, 96).
The constructor must be a public property, otherwise it cannot be called when the object is created. Of course, setting to private and protected properties will not report an error, but it is meaningless.
Constructors have no return value, and since there are no variables to receive the return value, it would be useless to have one, which means:
Whether it is a declaration or a definition, the return value type cannot appear before the function name, even void is not allowed;
There cannot be a return statement in the function body.
Constructor overloading
Like ordinary member functions, constructors are allowed to be overloaded. A class can have multiple overloaded constructors. When creating an object, it is determined which constructor to call based on the passed arguments.
The call of the constructor is mandatory. Once the constructor is defined in the class, it must be called when the object is created. It is an error not to call. If there are multiple overloaded constructors, the arguments provided when the object is created must match one of the constructors; conversely, only one constructor will be called when the object is created.
For the code in Example 1, it is wrong to write Student stu or new Student, because the class contains a constructor that is not called when the object is created.
Change the code of Example 1 to add one more constructor (Example 2):
#include <iostream>
using namespace std;
class Student{
private:
char *m_name;
int m_age;
float m_score;
public:
Student();
Student(char *name, int age, float score);
void setname(char *name);
void setage(int age);
void setscore(float score);
void show();
};
Student::Student(){
m_name = NULL;
m_age = 0;
m_score = 0.0;
}
Student::Student(char *name, int age, float score){
m_name = name;
m_age = age;
m_score = score;
}
void Student::setname(char *name){
m_name = name;
}
void Student::setage(int age){
m_age = age;
}
void Student::setscore(float score){
m_score = score;
}
void Student::show(){
if(m_name == NULL || m_age <= 0){
cout<<"The member variable has not been initialized"<<endl;
}else{
The age of cout<<m_name<<" is "<<m_age<<", and the grade is "<<m_score<<endl;
}
}
int main(){
//call the constructor Student(char *, int, float)
Student stu("Xiao Ming", 15, 92.5f);
stu.show();
//call the constructor Student()
Student *pstu = new Student();
pstu -> show();
pstu -> setname("Li Hua");
pstu->setage(16);
pstu -> setscore(96);
pstu -> show();
return 0;
}
operation result:
Xiao Ming's age is 15 and his grade is 92.5
member variable has not been initialized
Li Hua's age is 16 and his grades are 96
The constructor Student(char *, int, float) assigns values to each member variable, and the constructor Student() sets the value of each member variable to null, which is an overload relationship. When creating an object according to Student(), it will not assign valid values to member variables, so you also need to call member functions setname(), setage(), setscore() to reassign them.
Constructors are used a lot in actual development, and they are often used to do some initialization work, such as assigning values to member variables, opening files in advance, and so on.
default constructor
If the user does not define a constructor, the compiler will automatically generate a default constructor, but the function body of this constructor is empty, has no formal parameters, and does not perform any operations. For example, for the Student class above, the default generated constructor is as follows:
Student(){}
A class must have a constructor, either defined by the user or generated automatically by the compiler. Once the user defines the constructor, no matter how many or how the parameters are, the compiler will no longer automatically generate it. In example 1, the Student class already has a constructor Student(char *, int, float), which is defined by ourselves, the compiler will not add an additional constructor Student(), in example 2 we manually Added this constructor.
In fact, the compiler will only generate a default constructor when necessary, and its function body is generally not empty. The purpose of the default constructor is to help the compiler with initialization, not the programmer. This is the internal implementation mechanism of C++. I won't go into details here. Beginners can understand it according to the above-mentioned "there must be a default constructor with an empty function body".
One last thing to note is that it is also possible to omit the parentheses when calling a constructor with no arguments. For the code in Example 2, creating an object on the stack can be written as Student stu() or Student stu, and creating an object on the heap can be written as Student *pstu = new Student() or Student *pstu = new Student, both of which call the constructor Student ( ).
We did this in the past. We didn't write the parentheses when we created the object, but actually called the default constructor.