Dig into the constructor in C++
- 2020-05-05 11:30:39
- OfStack
C++ constructor
When creating an object, often needs to do some initialization, such as assigning values to data members. To solve this problem, C++ provides a constructor.
The constructor (Constructor) is a special member function that has the same name as the class name, returns no value, does not need to be called by the user (nor can the user), and is executed automatically when an object is created. Constructors are used to initialize objects when they are created, most commonly by assigning values to member variables.
An example of a constructor:
#include <iostream>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
// Declaration constructor
Student(char *, int, float);
// Declare ordinary member functions
void say();
};
// Define the constructor
Student::Student(char *name1, int age1, float score1){
name = name1;
age = age1;
score = score1;
}
// Define normal member functions
void Student::say(){
cout<<name<<" The age is "<<age<<" , the result is "<<score<<endl;
}
int main(){
// Create the object from the constructor
Student stu(" Xiao Ming ", 15, 90.5f); // The argument form is similar to a function call
stu.say();
return 0;
}
Results:
Xiao Ming's age is 15 , the result is 90.5
In the class we define a constructor, Student(), that assigns values to the three member variables of the private attribute. In the main function, we create an object stu based on the constructor; Because the constructor has arguments, arguments are passed in when the object is created, similar to a function call.
Note that once a constructor is defined in a class, the object must be created. If the constructor has arguments, arguments are passed when the object is created.
In addition, the constructor is mainly used for initialization and does not return a value (having a return value does not make any sense), which means:
No return value type is allowed before a function name, whether declared or defined, even by void.
You cannot have an return statement in the body of a function.
The default constructor is
If the user does not define a constructor himself, the compiler automatically generates a default constructor whose body is empty, takes no arguments, and does nothing. For the Student class above, the default generated constructor is
Student(){}
A class must have a constructor, either defined by the user or generated automatically by the compiler. Once the user defines the constructor himself, the compiler no longer generates it automatically, whether it belongs to the public attribute, private, protected, or private attributes. The Student class above has only one constructor, which we define ourselves.
In fact, the compiler generates the default constructor only when necessary, and its body is generally not empty. The purpose of the default constructor is to help the compiler do the initialization, not the programmer. This is the internal implementation mechanism of C++, and I won't go into details here. Beginners can understand this by saying, "there must be a default constructor for an empty function body."
Constructor overload
Like regular member functions, constructors are allowed to be overloaded. A class can provide multiple constructors for the user to select when an object is created, and the compiler determines which constructor to call based on the parameters passed when the object is created. In other words:
Only one constructor is executed;
The arguments provided when the object is created must match one of the constructors, otherwise the compilation will fail.
An example of constructor overloading:
#include <iostream>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
// Declaration constructor
Student();
Student(char *, int, float);
// Declare ordinary member functions
void setname(char *);
void setage(int);
void setscore(float);
void say();
};
// Define the constructor
Student::Student(){}
Student::Student(char *name1, int age1, float score1){
name = name1;
age = age1;
score = score1;
}
// Define normal member functions
void Student::setname(char *name1){
name = name1;
}
void Student::setage(int age1){
age = age1;
}
void Student::setscore(float score1){
score = score1;
}
void Student::say(){
cout<<name<<" The age is "<<age<<" , the result is "<<score<<endl;
}
int main(){
// Member variables are initialized when an object is created
Student stu1(" Xiao Ming ", 15, 90.5f);
stu1.say();
// Call the member function to initialize the value of the member variable
Student stu2;
stu2.setname(" Li lei ");
stu2.setage(16);
stu2.setscore(95);
stu2.say();
return 0;
}
Results:
Xiao Ming's age is 15 , the result is 90.5
Li lei's age is 16 , the result is 95
Class defines two constructors, one with an argument and one without, which are overloaded relationships. When objects are created from a constructor with no arguments, no arguments are passed, and the member variables are not initialized, so the member functions are called to set their values.
C++ constructor
with arguments
A constructor with no arguments gives each object of the class the same initial value.
If you want to assign different initializations to different objects, you need to use constructors with arguments to pass different data to constructors for different initializations when the constructors of different objects are called.
The general format of the constructor header is
Constructor name ( type 1 parameter 1, type 2 parameter 2, ... )
Since the user cannot call the constructor, it is impossible to give arguments in the normal way of calling a function. Arguments are given when an object is created. The general format for creating an object is
The name of the class Object name ( The arguments 1, The arguments 2, ... );
There are two long square columns whose length, width and height are 12, 20, 25 and 10, 14 and 20 respectively. Write an object-based program that USES a constructor with arguments in the class.
#include <iostream>
using namespace std;
class Box
{
public :
Box(int,int,int);
int volume( );
private :
int height;
int width;
int length;
};
// Declare a constructor with arguments // Declare a function of the calculated volume
Box::Box(int h,int w,int len) // Define a constructor with arguments outside the class
{
height=h;
width=w;
length=len;
}
int Box::volume( ) // Define a function to compute the volume
{
return (height*width*length);
}
int main( )
{
Box box1(12,25,30); // Object to establish box1 And specify box1 Length, width, and height
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(15,30,21); // Object to establish box2 And specify box2 Length, width, and height
cout<<"The volume of box2 is "<<box2.volume( )<<endl;
return 0;
}
The program runs as follows:
The volume of box1 is 9000
The volume of box2 is 9450
You can see:
A parameter in a constructor whose corresponding arguments are given when defining an object.
This method makes it easy to initialize different objects differently.
Initialize
The above is about initializing data members in the constructor's body with an assignment statement. C++ also provides another way to initialize data members -- parameter initialization tables to initialize data members. This method does not initialize the data member in the body of the function, but is implemented at the beginning of the function.
The constructor defined in the example can be used in the following form:
Box::Box(int h,int w,int len):height(h),width(w), length(len){ }
This method is convenient and concise, especially when more data members need to be initialized. Constructors can even be defined directly in the body of a class, rather than outside the class.