7782

Different ways of using C++ constructors

Question:

What the difference between A a1(5); and A a2 = A(5) ? Both of the works, but I really want know the difference between them, because I used method 2 in one of my project and I suffered from a bug which is fixed after I change to method 1. Thanks in advance!

class A { public: int val; A() : val(0) {} A(int newVal) : val(newVal) {} }; int main() { A a1(5); // method 1 A a2 = A(5); // method 2 }

Answer1:

A a1(5); // method 1 A a2 = A(5); // method 2

The first one is called direct initialization, the second one is called copy-initialization.

The second one will NOT compile if you make the copy-constructor inaccessible or/and don't define it as:

class A { public: int val; A() : val(0) {} A(int newVal) : val(newVal) {} private: A(A const&); //the second one will not compile };

Now the second one will not compile. Note that it will not compile in both cases:

<ul><li>If the copy-constructor is defined, but is inaccessible (either it is private or protected).</li> <li>If the copy-constructor is declared, but not defined.</li> </ul>

Answer2:

Strictly speaking, reading your question I expected you to provide these two examples

A a1(5); // method 1 A a2 = 5; // method 2

The first one is direct-initialization. The second one is copy-initialization.

The examples <em>you</em> provided in your question actually <em>already</em> illustrate the difference between the two :)

Direct-initialization initializes the target object directly, as a single-step process by finding and using an appropriate constructor. Copy-initialization is conceptually a two-step process: first it constructs a temporary object of type A by some conversion constructor and then it copies it to the destination object by using a copy-constructor. I.e.

A a2 = 5;

will actually work as

A a2 = A(5);

And that actually exhaustively explains the difference.

The two-step structure of the second variant is, again, conceptual. The compilers are allowed (and will) optimize the second variant so that it will work exactly as the first one. They will eliminate the intermediate temporary object and perform initialzation directly.

Recommend

  • CodenameOne - Android app fails to start when building with android.buildToolsVersion=27
  • ASP.net get content page to change master page control
  • TFS API: How to check if a work item has been deleted or is non existent on the TFS Server? (not if
  • How to use a customized directory location for installing R packages
  • ToolStripCombobox.SelectionChangeCommitted not found
  • What does the TypeScript “lib” option really do?
  • Vigenere cipher not working
  • Add reference to ASP.NET 5 Class Library from Framework 4.5 Class Library Project
  • How can we prepend rows to a react native list-view?
  • Can I use AllJoyn Framework for Wifi Direct in iOS?
  • Most efficient way to move table rows from one table to another
  • unable to get jsonEncode in magento2
  • Struts 2 TextField Tag with an attribute and no value
  • NUnit 3.0 TestCase const custom object arguments
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • std::remove_copy_if_ valgrind bytes in block are possibly lost in loss record
  • Silverlight DependencyProperty.SetCurrentValue Equivalent
  • How can I set a binding to a Combox in a UserControl?
  • C: Incompatible pointer type initializing
  • Create DicomImage from scratch using Dcmtk
  • Groovy: Unexpected token “:”
  • Functions in global context
  • Sencha Touch 2.0 Controller refs attribute not working?
  • Google Custom Search with transparent background
  • When to use `image` and when to use `Matrix` in Emgu CV?
  • What is the “return” in scheme?
  • Read text file and split every line in MSBuild
  • output of program is not same as passed argument
  • Which linear programming package should I use for high numbers of constraints and “warm starts” [clo
  • Javascript + PHP Encryption with pidCrypt
  • Why winpcap requires both .lib and .dll to run?
  • XCode can't find symbols for a specific iOS library/framework project
  • How to set the response of a form post action to a iframe source?
  • Angular 2 constructor injection vs direct access
  • Getting Messege Twice Using IMvxMessenger
  • Qt: Run a script BEFORE make
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android
  • How can i traverse a binary tree from right to left in java?
  • How can I use threading to 'tick' a timer to be accessed by other threads?