Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird c++ copy constructor without default constructor [duplicate]

Me and a colleague of mine had a debate about wether

Pt pt;

and

Pt pt = Pt(); 

are equivalent. I suspected that in the second case copy assignment could be called, but as it turns out it isn't the case.

As we ran our little experiment I decided to test a weird bit, that my colleague thought wouldn't even compile:

//here the compiler calls a copy constructor and doesn't call the default constructor prior to that
// O_o
Pt pt = pt;

Here is a working sample: http://ideone.com/XmJSz7

So, the question is - what goes on in:

Pt pt = pt;
like image 368
mr.pd Avatar asked May 13 '15 10:05

mr.pd


1 Answers

Constructions like type object = something call copy constructors, not assignment operators

Having this in mind, here's what happens:

  1. Pt pt = -> at this point, Pt object is created, named pt (nothing is initialized at this point)
  2. = pt; -> at this point, pt's copy constructor is called with argument - itself (pt)
  3. as pt is created BUT not initialized (in 1.), this is (kinda) valid - pt's copy constructor (in 2.) will be "properly" executed, taking as right-hand-side argument the already existing and uninitialized object pt (from 1. again)

Shortly - this is bad.

It's worth noting, that if the pt object is global or static, it will be default-initialized at step 1. - after reaching the =.

EDIT: regarding the initial "puzzle" Pt pt = Pt();, you can see this question: Is there a difference in C++ between copy initialization and direct initialization? and its accepted answer. And this one seems interesting, too: How variable is initialized by default constructor in c++

like image 71
Kiril Kirov Avatar answered Sep 29 '22 01:09

Kiril Kirov