C++ Programming

Constructor with parameters and constructor Overloading in C++ with examples

Use the constructor to initialize the class object

Object initialization

Constructor:- It is often necessary to assign initial values ​​to variables in the program, that is, to initialize them. This is easy in process-oriented programs Realize, assign initial value when defining variable. Such as

int a = 10;

In an object-based program, when defining an object, initialization is also required, that is, assign initial values ​​to data members. An object represents an entity, and each object has certain properties. For example, there is a Time class (time), use it to define Meaning objects u, t2, 3. Obviously, 1, t2, and 3 respectively represent 3 different times (hour, minute, second). Every object It should have a certain content when it is established, otherwise it will lose the meaning of the object. Allocate memory for objects in the system At the same time, the relevant data members should be assigned initial values ​​at the same time. So, how to make them get initial values? Someone tried to initialize the data members when declaring the class. Such as

allpcb circuit


This is wrong. Because a class is not an entity, but an abstract type, it does not occupy storage space, and obviously has nowhere. Accept data. If all members in a class are public, you can initialize the data members when defining the object. Such as

This situation is similar to the initialization of structure variables. List the public data members in a curly brace. Value, separated by comma between two values. However, if the data member is private, or there is private or Protected data members cannot be initialized in this way. member functions are used to assign initial values ​​to data members in objects. If multiple objects are defined for a class, and there are more data members in the class, then the program appears Very cumbersome and cumbersome, where is the quality and efficiency of such a program? A convenient way should be found the data members are initialized.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Use constructor to initialize data members

In C++ programs, the initialization of objects is an indispensable problem. Shouldn’t make programmers in this problem Too much energy is spent on it, C++ provides a better way to deal with the design of the class. In order to solve this problem, C++ provides a constructor to handle the initialization of the object. structure Function is a special kind of member function. Unlike other member functions, it does not require the user to call it. It is automatically executed when it is imaged. The constructor is defined by the designer of the class when the class is declared, and the program user only you must specify the initial value of the data member while defining the object.

The name of the constructor must be the same as the name of the class, rather than arbitrarily named, so that the compilation system can recognize it Treated as a constructor. It does not have any type and does not return any value. First observe the following example.

Example 1: use the constructor to assign initial values ​​to the data members of the object:

Program analysis:

The constructor Time is defined in the class, which has the same name as the class. Automatically execute the constructor when creating the object According to the definition of the constructor Time, its function is to assign an initial value of 0 to all data members in the object. Don’t Misunderstanding is that the initial value of the program data member is directly assigned when the class is declared (that is not allowed), and the assignment statement is written in the structure In the function body of the function Time, these assignment statements are executed only when the constructor Time is called. Assign values ​​to data members in the object. When the main function is executed, the object is first created, and the constructor Time is automatically executed at this time. Executing constructor The initial value 0 is assigned to the data member in the tl object during Time. Then execute the l, set_time function in the main function, Input a new value from the keyboard and assign it to the data member of the object, and then output the value of the data member. Then create object t2,



At the same time, the constructors Time is automatically executed, and the initial value 0 is assigned to the data member in t2. But there is no number for t2 in the main function Assign a new value according to the member, and directly output the initial value of the data member. The above is to define the constructor in the class, or you can only declare the constructors in the class and define it outside the class Constructor. Change lines 4 to 7 in the program to the following line:

Time();

Define the constructor outside the class:

Regarding the use of the constructor, there are the following instructions:

(1) When is the constructors called? The constructor is automatically called when the class object is created. In the establishment of When the system allocates storage units for the object, when the constructor is executed, the specified initial value is sent to the relevant data Member’s storage unit. Every time an object is created, the constructor is called once. In the above program, in the main An object is defined in the function. At this time, the constructor Time in the t1 object is automatically called to make each data into The value of the member is 0.

(2) The constructor has no return value, its role is only to initialize the object. So there is no need to define The type is declared when constructing a function, which is an important difference between it and a general function. Cannot be written as

int Time () {….}

or

void time() {…}

(3) The constructor does not need to be called by the user, Nor can it be called by users. The following usage is wrong:

t1.Time ();

The constructor is automatically executed by the system when the object is defined, and it can only be executed once. Constructor general sound Ming is public.

(4) One class object can be used to initialize another class object, such as

Time t1;

Time t2 =t1;

At this time, the value of each data member of the object is copied to the corresponding member of t2 without calling the constructor t2. Time().

(5) In the function body of the constructor, not only can initial values ​​be assigned to data members, but also other statements can be included, such as Such as cout statement. However, it is generally not recommended to add content that has nothing to do with initialization in the constructor to maintain the program’s clear.

(6) If the user does not define a constructor, the C++ system will automatically generate a constructor, but The body of this constructor is empty, has no parameters, and does not perform initialization.


Constructor with parameters

In Example 1, the constructor takes no parameters, and the data members are assigned initial values ​​in the function body. This way makes this kind of The data members of each object are Get the same set of initial values ​​(for example, the initial values ​​of the data members of each object in Example 1 are average Is 0). However, sometimes users want to assign different initial values ​​to different objects, then the above method cannot be used.

To solve it. The constructor with parameters can be used. When the constructor of different objects is called, different data is transmitted from the outside. Passed to the constructor to achieve different initialization. The general format of the constructor header is Constructor name (type 1 formal parameter 1 type 2 formal parameter 2….)

As explained earlier: the user cannot call the constructor, so the conventional method of calling functions cannot be used to give Output the actual parameters (such as fun(a,b);). The actual parameters are given when the object is defined. The general format for defining objects is Class name object name (actual parameter 1 actual parameter 2….);

When the object is created, the actual parameter values ​​are passed to the corresponding formal parameters of the constructor, and they are used as the initial values ​​of the data members.

Example 2 There are two rectangular columns whose height, width and length are (1) 12, 20, 25; (2) 10, 14, 20.

Program analysis:

The constructor Box has 3 parameters (h, w, 1), which represent height, width, and length. Define the object box1 in the main function At the same time, the actual parameters 12, 25, 30 of the function are also given. The system automatically calls the constructor Box in the object box1. Real combination, assign the height, width, and length in box1. Then the function is called by the cout statement in the main function Count box1.volume(), and output the volume of box1. The same is true for box2.

Note: The statement form for defining an object is Box box1 (12,25,30);

Know:

(1) For the formal parameters in the parameterized constructor, the corresponding actual parameters are given when the object is created. Is establishing Specify the initial value of the data member at the same time as the object.

(2) The actual parameters used when defining different objects are different, and they reflect the properties of different objects. This method can be In order to easily implement different initializations for different objects. This method of initializing objects, It is very convenient and intuitive to use. See data members directly from the definition statement The initial value.


Initialize data members with parameter

it is introduced in the function body of the constructor to implement initial data members through assignment statements. C++ also provides another method of initializing data members-parameter initialization table to achieve the data member initialization. This method does not initialize the data members in the function body, but in the function header achieve. For example, Example 2 The constructor defined in can be changed to the following form: Box::Box (int n, int w, int len):height (h), width (w), length (len) {} That is, add a colon to the end of the original function header, and then list the parameter initialization table. The initialization table above indicates: Initialize the data member height with the value of the formal parameter h, initialize the data member width with the value of the formal parameter w, and use the value of the formal parameter len Value initialization data member length. The curly braces after it are empty, that is, the function body is empty and there is no execution statement.

The effect of this form of constructor is the same as the Box constructor defined outside the class in Example 2. Initially using parameters The initializing table method can reduce the length of the function body and make the structure function appear concise and simple. So that you can directly in the class body (Not outside the class) define the constructor. Especially when there are many data members that need to be initialized, its superiority is more obvious. Many C++ programmers like to initialize all data members in this way. The general form of the constructor with parameter initialization table is as follows:

Class name::Constructor name ([parameter table])[:member initialization table]

{

[Constructor body]

}

The square brackets are optional (optional). Note: If the data member is an array, it should be assigned with a statement in the function body of the constructor, but not Initialize it in the parameter initialization table. Such as

class Student

{

public: Student (int n, char s,nam[]) :num, sex (s)

{strcpy (name, nam);

}

private:

int num;

char sex;

char name [20];

};

You can define the object stud1 like this:

Student stud1 (1001,’m’, “fawad khan”); Using the initialization table, assign the value 1001 obtained by the formal parameter to the private data member num, and assign the value ‘m’ obtained by the formal parameter For sex, copy the value of each element of the shape parameter group nam to the name array through the strcpy function. Such objects All data members in stud1 are initialized, and this object has certain content.

Overloading of the constructor

Multiple constructors can be defined in a class to provide different initialization methods for the object for users to choose use. These constructors have the same name, but the number of parameters or the types of parameters are not the same, this is called a constructor Overloaded. The knowledge of function overloading. Through the following example, you can understand how to apply the overloading of the constructor.

Example 3: define two constructors, one of which has no parameters and the other has parameters:


Program analysis:

A parameter less constructor Box is declared in the class, and private data members are assigned in the function body defined outside the class.The second constructor Box is defined directly in the class body, and initializes the data members with the parameter initialization table. This function has 3 parameters and requires 3 actual participation. The two constructors have the same name (both are Box), then the system How to distinguish which constructor is called? It is to determine which constructor corresponds to according to the form of function call function. In the main function, no parameters are given when the object box1 is created, and the system finds the corresponding parameter less constructor Box, the result of executing this constructor is to make the values ​​of the 3 data members all 10. Then output the volume of box1 1000.

When the object box2 is created, 3 actual parameters are given, and the system finds the constructor Box with 3 formal parameters corresponding to it. The result of executing the constructor is to make the values ​​of the 3 data members 15, 30, 25. Then output the body of box2 Product 11250.

Two constructors with the same name are defined in this program, in fact, more overloaded constructors can be defined. example For example, there can also be the following constructor prototypes:

Box:: Box (int h);

Box :: Box (int n, int w);

One parameter and two parameters can be given when creating an object, and the system will call the corresponding constructor respectively.

Description:

(1) It is not necessary to give the actual parameter constructor when creating the object, which is called the default constructor (default Constructor). Obviously, The parameter less constructor belongs to the default constructor. A class can only have one default constructor number. If the user does not define a constructor, the system will automatically provide a default constructor, but its function body is empty , Does not have an initialization effect. If the user wants to make the data members have initial values ​​when creating the object, they must set their own Definition constructor.

(2) If the parameter less constructor is selected when creating the object, attention should be paid to correctly writing the sentence defining the object.

For example, there are the following statements that define objects in this program:

Box box1;

Box box1 ();

The above statement does not define the object box1 of the Box class, but declares a normal function box1, the return of this function Value is Box type. There should be no call to parameter less constructors (such as Box() ) in the program, please remember: the constructor is Cannot be explicitly called by the user.

(3) Although multiple constructors can be included in a class, for each object, when the object is created Only one of the constructors is executed, not every constructor is executed.

Constructor with default parameters

The value of the parameter in the constructor can be passed through the actual parameter or specified as some default value, that is, if the user does not Specify the actual parameter value, the compiler system will make the value of the formal parameter default value. In real life, there are often some initial values ​​like this: The initial value of the counter is generally 0 by default. Gender generally defaults to “male”, weather defaults to “sunny”, etc. If it is true If the actual situation is not these values, it will be specified by the user. This can reduce the amount of input. Also in the constructor This method can be used to achieve initialization. For example, the problem in Example3 can also use a structure with default parameters. Create functions to deal with.



Example 5: Change the constructor in the program of Example 3 to use parameters with default values. The default values ​​for width, height, and length are all 10. Rewrite on the basis of the program in Example 3.

Program analysis:

Since no actual parameters are given when defining the object box1, the system calls the default constructor, and the value of each formal parameter is defaulted. Accepted value 10. which is box1.height = 10;

Box1.width=10;

box1.length=10;

When defining the object box2, only one actual parameter 15 is given, which is passed to the parameter h (the height of the rectangular column), and the parameters w and len are not The value from the actual parameter is the default value of 10. which is

box2.height =15;

box2.width=10;

box2.length=10;

Similarly:

box3.height = 15;

box3.width = 30;box3.length=10;

box4.height =15;

box4.width=30;

box4.length=20;

The definition of the constructor in the program (lines 12 to 16) can also be rewritten in the form of a parameter initialization table:

Box::Box (int n, int w, int len): height (h), width (w), length (len) { } Just one line is enough, simple and convenient.

It can be seen that it is convenient and effective to use default parameters in the constructor, and it provides a lot of This option is equivalent to several overloaded constructors. Its benefits are: even when calling the constructor No actual parameter value is provided, not only will there be no error, but also ensure that the object is initialized according to the default parameter value. especially It is more convenient to use this method when you want to have the same initialization status for each object, no need to enter data, the object All are initialized with the values ​​specified in advance.

Description:

(1) Where should the default parameters of the constructor be specified? The default values ​​are specified when the constructor is declared, and You cannot just specify default values ​​when defining the constructor. Because the class definition is placed in the header file, it is an external to the class The user can see the mouth, and the definition of the function is the implementation detail of the class, and the user often can’t see it. In the statement structure Specify default parameter values ​​when creating a function so that users know how to use the default parameters when creating an object.

(2) When declaring the constructor on line 5 of the program, the parameter name can be omitted, that is, written as Box (int = 10, int = 10, int = 10);

(3) If all the parameters of the constructor are assigned default values, you can give one or several Actual parameters can also be omitted. Since the constructor can be called without actual parameters, all parameters are specified The default constructor also belongs to the default constructor. As mentioned earlier: a class can only have one default constructor Number, that is, a class can only have one constructor that can be called without parameters. The reason is obvious, It is to avoid ambiguity when calling. If the following two constructors are defined at the same time, it is wrong.


Box();

Box (int = 10, int =10, int =10);

When creating an object, if you write

Box box1;

The compilation system cannot identify which constructor should be called, and there is ambiguity, and an error is reported during compilation. Should avoid this Happening.

(4) After a constructor with all default parameters is defined in a class, no overloaded constructors can be defined. For example, there are the following constructors declarations in a class:

Box (int = 10, int = 10, int = 10);

Box();

Box (int,int);

If there is the following definition statement:

Box box1;

Box box2 (15,30);

Which constructors should be executed? There is ambiguity. But if the parameters in the constructor are not all default When it is worthwhile, it is necessary to analyze the specific situation. If there are the following 3 prototype declarations:

Box();

Box (int, int = 10, int = 10);

Box (int,int);

One parameter is not the default parameter Constructors with two parameters If there are the following statements that define objects:

Box box1;

Box box2 (15);

Box box3 (15,30);

It is easy to make mistakes, so be very careful. Therefore, in general, the overload of the constructor and the construction with default parameters should not be used at the same time function.

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button