A deep explanation of the constructors in C + + _c language

Source: Internet
Author: User

C + + constructors
When you create an object, you often need to do some initialization work, such as assigning values to data members. To solve this problem, C + + provides a constructor.

A constructor (constructor) is a special member function that has the same name as the class name, does not have a return value, does not require a user call (nor can it be invoked by the user), but is automatically executed when the object is created. The function of a constructor is to initialize the object when it is created, and the most common is to assign a value to a member variable.

An example of a constructor:

#include <iostream>
using namespace std;
Class student{
private:
  char *name;
  int age;
  float score;
Public:
  //Declare constructor
  Student (char *, int, float);
  Declares the ordinary member function
  void Say ();
Define constructor
Student::student (char *name1, int age1, float score1) {
  name = name1;
  age = Age1;
  Score = Score1;
}
Define the normal member function
void Student::say () {
  cout<<name<< "is" <<age<< ", the result is" <<score <<endl;
}
int main () {
  ////Create object based on constructor
  Student Stu ("Xiaoming", 90.5f);//Parameter form is similar to function call
  Stu.say ();
  return 0;
}

Run Result:

Xiaoming's age is 15, and his grade is 90.5.

In the class we define a constructor Student (), which is to assign values to the member variables of 3 private properties. In the main function, we create an object Stu based on the constructor, because the constructor has parameters, so the arguments are passed in when the object is created, similar in form to a function call.

The reader should note that once the constructor is defined in the class, the object is created to be executed, and if the constructor has parameters, the object is to be called when it is created.

In addition, constructors are primarily used for initialization, there is no return value (there is no meaning to the return value), which means:
The return value type cannot appear before the function name, whether declared or defined, even if void is not allowed;
You cannot have a return statement in a function body.
Default constructor

If the user does not define a constructor on his own, the compiler automatically generates a default constructor, except that the function body of the constructor is empty and has no parameters and does not perform any action. For example, the Student class above, the default generated constructor is as follows:

Student () {}


A class that must have constructors, either defined by the user itself, or generated automatically by the compiler. Once the user has defined the constructor itself, whether it is public or private, protected properties, the compiler is no longer automatically generated. The Student class above, with only one constructor, is defined by ourselves.
In fact, the compiler generates a default constructor only when necessary, and its function body is generally not empty. The purpose of the default constructor is to help the compiler do the initialization work, not to help the programmer. This is the internal implementation of C + + mechanism, here no longer delve, beginners can follow the above said "must have an empty function body default constructor" to understand.
Overloading of constructors

As with normal member functions, constructors are allowed to be overloaded. A class can provide multiple constructors that allow a user to choose when creating an object, and the compiler determines which constructor is invoked based on the parameters passed when the object is created. Other words:
Only one constructor is executed;
The arguments provided when the object was created must match one of the constructors, or compile incorrectly.

An example of a constructor overload:

#include <iostream>
using namespace std;
Class student{
private:
  char *name;
  int age;
  float score;
Public:
  //Declare constructor
  Student ();
  Student (char *, int, float);
  Declares the ordinary member function
  void SetName (char *);
  void setage (int);
  void SetScore (float);
  void say ();
Define constructor
Student::student () {}
student::student (char *name1, int age1, float score1) {
  name = name1;
  age = Age1;
  Score = Score1;
}
Defines the normal member function
void Student::setname (char *name1) {
  name = name1;
}
void student::setage (int age1) {Age
  = Age1;
}
void Student::setscore (float score1) {
  score = score1;
}
The Age of Void Student::say () {
  cout<<name<< is "<<age<<" and the result is "<<score<<endl;}".
int main () {
  //When creating an object initializes the member variable
  Student stu1 ("Xiaoming", 90.5f);
  Stu1.say ();
  
  Call a member function to initialize the value of a member variable
  Student STU2;
  Stu2.setname ("Li Lei");
  Stu2.setage ();
  Stu2.setscore ();
  Stu2.say ();
  return 0;
}

Run Result:

Xiaoming's age is 15, the result is 90.5
Li Lei's age is 16, the result is 95

A class has two constructors defined, one with a parameter and one without arguments, which is an overloaded relationship. When an object is created based on a constructor without parameters, no arguments are required, and member variables are not initialized, so call member functions to set their values.

C + + constructor with parameters
A constructor with no arguments causes each object of the class to have the same initial value.

If you want to assign different initial values to different objects, you need to use a constructor with parameters to pass different data to the constructor when you invoke the constructors of different objects to achieve different initialization.

The general format for the first part of the constructor is:

  Constructor name (type 1 parameter 1, type 2 parameter 2, ...)


Because a user cannot invoke a constructor, it is not possible to give an argument with a normal method of calling a function. The argument is given when the object is created. The general format for creating objects is:

  Class Name Object name (argument 1, Argument 2, ...);

"Example" has two rectangular columns, its length, width, height, respectively, 12, 20, 25 and 10, 14, 20, to find their volume. Write an object-based program that uses a constructor with parameters in the class.

#include <iostream>
using namespace std;
Class box
{public
  :
  box (int,int,int);
  int volume ();
  Private:
  int height;
  int width;
  int length;
};
Declares a constructor with parameters//declaring a function of the calculated volume
box::box (int h,int w,int len)//define a constructor with parameters {Height=h outside the class
  ;
  Width=w;
  Length=len;
}
int Box::volume ()//defines the function of the calculated volume
{return
  (height*width*length);
}
int main ()
{
  Box box1 (12,25,30);//Create Object Box1 and specify Box1 long, wide, high value
  cout<< "The volume of Box1 is" << Box1.volume () <<endl;
  Box Box2 (15,30,21); Creates an object Box2 and specifies a box2 long, wide, high value
  cout<< "The volume of Box2 is" <<box2.volume () <<endl;
  return 0;
}

The results of the program operation are as follows:

The volume of box1 is 9000 the
volume of Box2 is 9450

Can know:
A formal parameter in a constructor with parameters, and its corresponding argument is given when the object is defined.
In this way, different initialization of different objects can be implemented conveniently.
Class with the parameter initialization table for the data member.

The above is the initialization of data member implementations through assignment statements in the function body of a constructor. C + + also provides another way to initialize data members-the parameter initialization table to initialize the data members. This method does not initialize the data member in the function body, but is implemented in the first part of the functor.

example, you can use the following form to define a constructor:

  Box::box (int h,int w,int len): Height (h), Width (w), Length (len) {}


This kind of writing is convenient and concise, especially when the data members need to be initialized are more obvious advantages. Constructors can even be defined directly in the class body, not outside the class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.