Which of the following member functions are used for initializing the member variables of an object?
Skip to main content This browser is no longer supported. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Special member functions
In this articleThe special member functions are class (or struct) member functions that, in certain cases, the compiler automatically generates for you. These functions are the default constructor, the destructor, the copy constructor and copy assignment operator, and the move constructor and move assignment operator. If your class does not define one or more of the special member functions, then the compiler may implicitly declare and define the functions that are used. The compiler-generated implementations are called the default special member functions. The compiler does not generate functions if they are not needed. You can explicitly declare a default special member function by using the = default keyword. This causes the compiler to define the function only if needed, in the same way as if the function was not declared at all. In some cases, the compiler may generate deleted special member functions, which are not defined and therefore not callable. This can happen in cases where a call to a particular special member function on a class doesn't make sense, given other properties of the class. To explicitly prevent automatic generation of a special member function, you can declare it as deleted by using the = delete keyword. The compiler generates a default constructor, a constructor that takes no arguments, only when you have not declared any other constructor. If you have declared only a constructor that takes parameters, code that attempts to call a default constructor causes the compiler to produce an error message. The compiler-generated default constructor performs simple member-wise default initialization of the object. Default initialization leaves all member variables in an indeterminate state. The default destructor performs member-wise destruction of the object. It is virtual only if a base class destructor is virtual. The default copy and move construction and assignment operations perform member-wise bit-pattern copies or moves of non-static data members. Move operations are only generated when no destructor or move or copy operations are declared. A default copy constructor is only generated when no copy constructor is declared. It is implicitly deleted if a move operation is declared. A default copy assignment operator is generated only when no copy assignment operator is explicitly declared. It is implicitly deleted if a move operation is declared. See alsoC++ Language Reference FeedbackSubmit and view feedback for Constructors are, first and foremost, just functions. They can be simple, complex, or anything in between. However, constructors are special functions that are called automatically whenever a new object is created (i.e., instantiated). The primary purpose of constructors is to construct or initialize an object. Visually, constructors are set apart from "regular" functions by two characteristics: (a) they have the same name as the class for which they are constructing objects, and (b) they do not have a return type. Initializer lists are used with constructors to initialize (i.e., assign the first or initial value to) an object's member variables. Before the ANSI 2014 standard, initializer lists were the only way to initialize member variables, and they remain the preferred way to initialize data members with values passed into the constructor as arguments. ConstructorsAs you might guess, constructors are a pretty important part of object-oriented programs. Constructors are essential enough that five different kinds are independently named to make them easier to talk about.
Each constructor is designed to fill a specific programming need, but most classes will only need a few constructors - not all. The following sections describe each kind of constructor in detail, but the focus is on the constructor's visible operations. One object-oriented feature, polymorphism, requires that each object store a hidden pointer (called the vptr or virtual pointer). One of the tasks of every constructor is to initialize the vptr pointer, which it does by running code that the compiler automatically inserts into each constructor. If the class does not have any constructors, the compiler creates a simple default constructor to initialize the vptr. The Default ConstructorThe primary characteristic that sets a default constructor apart from the other constructors is that it does not have any parameters. A default constructor is often used to create an "empty" object or an object initialized with default values. Although the textbook didn't state it at the time, many of our previous examples have relied on the string class default constructor. The string default constructor creates a string object that does not contain any characters. We can also use a default constructor to create an "empty" instance of our Time class:
Conversion ConstructorA conversion constructor converts one data type into an instance of the class in which the constructor appears. What the conversion means and how the conversion function works depends very much on the source and destination types. A conversion constructor has one argument and the one highlighted in the following example converts an int into an instance of the Time class: class Time { private: int hours; int minutes; int seconds; public: Time(int s) { hours = s / 3600; s %= 3600; minutes = s / 60; seconds = s % 60; } }; A conversion constructor. This constructor converts an integer into an instance of Time (i.e., into a Time object)The conversion constructor illustrated above is the second make_time function from the struct Time example rewritten as a constructor. It is possible to generalize the pattern of a conversion constructor as follows: class Foo { . . . public: Foo(Bar b); // converts a Bar into a Foo };Where Bar may be the name of a primitive, built-in data type, or it may be the name of a class. Here is another example of a conversion constructor based on strings and C-strings: The definition of variable s converts a C-string ("Hello, World!") into the string object s. Copy ConstructorA copy constructor creates a new object by copying an existing object. C++ bases two critical and fundamental programming operations on the copy constructor:
This means that whenever functions pass or return objects by value, the program copies the objects from one part of the program to another. Each operation creates a new object, and constructing new objects is always the task of a constructor function. These operations are so fundamental to programming that the compiler automatically generates a copy constructor for every class. In the situations that we've seen so far, the task of copying an existing object is easy enough that the compiler can create the constructor. Later, we will see more complex situations where the compiler-generated copy constructor is insufficient, and, in such cases, we must override it with our own constructor. Since the copy constructor implements pass-by-value, the argument to the copy constructor cannot be passed by value (which would cause infinite recursion). For this reason, copy constructors have a particular signature that makes them easy to identify and which programmers must follow when they need to override the compiler-generated copy constructor. Copy constructors always take a single argument that is the same class type as the class in which the constructor appears, and the argument is always a reference variable: ClassName(const ClassName& o);
If one or more member variables is a pointer, the copy operation becomes more complex, and we defer dealing with this situation until the next chapter. For the curious or those facing a more immediate problem, please see The Copy Constructor in the next chapter.
Move ConstructorLike the copy constructor, the move constructor can be identified by its distinctive argument list: ClassName(ClassName&& o);If a move constructor has additional arguments, they must have default values (i.e., default arguments). Unlike copy constructors, move constructors can take some or all the resources held by the argument object rather than copying them. The argument object remains in a valid but potentially incomplete state. Our study of the move constructor will extend only to recognizing and identifying it. The double ampersand, &&, which denotes an r-value reference declarator, and the move constructor are otherwise beyond the scope of CS 1410, but you'll study them in detail in CS 2420. General ConstructorNo special syntax or pattern defines a general constructor. A general constructor simply does not fit into one of the previously described categories above. So, any constructor that has two or more parameters is a general constructor just because it's not (a) a default constructor (no parameters), (b) a conversion constructor (has one parameter that's not a reference), or (c) a copy constructor (one parameter that is a reference). It is possible to convert the first make_time function from the struct Time example into a general constructor: Time::Time(int h, int m, int s) { hours = h; minutes = m; seconds = s; } A general constructor. If it's not a default constructor, a conversion constructor, a copy constructor, or a move constructor, then it's a general constructorInitializer List NotationOne common task of constructor functions is initializing an object's member variables regardless of the constructor's overall complexity. Although member initialization can occur in the constructor's body, it is considered best practice to initialize members with an initializer list. An initializer list has the advantage of running before the function's body. So, the member variables are ready to use as soon as the constructor body runs. Initializer lists begin with a colon and appear between a function's parameter list and the body's opening brace. Initializer lists follow a simple pattern: class fraction { private: int numerator; int denominator; public: fraction(int n, int d) : numerator(n), denominator(d) {} }; Argument list notation. An argument list includes everything from the colon to (but not including) the opening brace of the empty function body. The symbols used in the initializer list are specific. The color coding shows the connection between the data members, the function arguments, and the symbols appearing in the initializer list.Constructors are the only functions that may have an initializer list, and the list is a part of the constructor's definition. So, if the function is prototyped in the class but defined elsewhere, the initializer list appears with the definition. An initializer list is a comma-separated list of initializer elements. Each element behaves like an assignment, so numerator(n) is equivalent to numerator = n. The color coding in the figure above highlights how each initializer element is formed: the first part of each element is the name of a member variable and the second part (enclosed in parentheses) is the name of one of the function's parameters. With one exception, the list elements may appear in any order, but a list element that initializes an inheritance relationship (i.e., calls a superclass constructor), must appear first in the list.
Every function must have exactly one body. The body is often empty in the case of very simple constructors whose only purpose is to initialize the object's member variables. In the following example, the {} at the end is the function's empty body and not part of the initializer list. Initializer lists are a part of the function definition and not of the declaration or prototype. So, if the class only contains a function prototype and the function definition is in a separate .cpp file, then the initializer list goes with the function definition in the .cpp file:
Caution:
Default ArgumentsAlthough the UML has always permitted class designers to specify initial values for both member variables and function arguments, C++ originally did not allow programmers to initialize member variables in the class specification. So, programmers initialized member variables with constructors, and you may still see examples of this in existing code. However, C++ has always supported default arguments, which may be used with any C++ function (not just constructors). When we use default arguments with constructors, they must follow all of the rules listed in chapter 6 (and it's probably a good idea to review those rules now).
In "real world" C++ programs, it is common for the class specification to appear in a .h file and the member functions (including constructors) to appear in a .cpp file. When we follow this organization, there is one unfortunate aspect of initializer lists and constructor default arguments that we must memorize:
Default Constructors and In-Class Initialization If a class only needs a constructor to initialize the member variables, replacing the constructor with initializations directly in the class specification is appropriate. The compiler will automatically create a default constructor to initialize the vptr as needed. However, initializing member variables directly inside the class specification does not take the place of a default constructor or default arguments when object construction requires operations more complex than member initialization. Furthermore, if the class defines one or more parameterized constructors, then a default constructor or default arguments are still needed if the programmer wishes to create an object without calling a parameterized constructor: fraction f1; fraction* f2 = new fraction;Constructor ChainingLike any function, constructors can range from algorithmically simple to complex. Sometimes complex constructors perform the same operations as simple ones, followed by additional operations befitting their complex nature. We can often avoid the overhead of writing and maintaining duplicate constructor code by putting the common, often simple, code in a basic constructor and allowing more advanced constructors to call the basic one. Java has always supported in-class constructor chaining by using this(...) as the name of an overloaded constructor and the number and type of arguments to differentiate between them. Before the adoption of the C++ 2011 standard, C++ did not permit in-class constructor chaining, but it does now, albeit with limitations.
Chaining constructors works well when the operations of the called or delegated constructor (e.g., (b)) must or can run before the operations in the calling or delegating constructor (e.g., (c)). When that is not the case, the best we can do in C++ or Java is use a helper function to implement the common code.
1 A bitwise copy simply means that the computer copies a patch of bits, bit-for-bit, from one memory location to another. The copy can be completed with the memcpy function, which is supported on many computers with a single machine instruction (and so is very fast and efficient). For example, given the following code fragment: class foo { . . . }; foo f1; foo f2; f1 = f2;The compiler-generated copy constructor implements the assignment operation as: memcpy(&f1, &f2, size of(foo));Back | Chapter TOC | Next What is used to initialize object?A constructor in Java is a block of code within a class that is used to initialize objects of class. In other words, a constructor is used to initializing the value of variables.
How do you initialize a member object in C++?There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
What is member initialization list in C++?Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
Where are the member variables of a class initialized?Member variables are always initialized in the order they are declared in the class definition.
What is a member variable What is a member function?In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).
|