In C++, what is the difference between something like: int i = 3; and int i(3); and which is better?
For intrinsic types, they're identical. Even for your own defined classes, they should result in the same code if no or an empty constructor is explicitly defined. However, consider this: class A { public: A() { for(int i=0; i<100000; i++) m_data += sqrtf(m_data); } A(const A &other) { m_data = other.m_data; } A &operator = (float val) { m_data = val; } private: float m_data; }; It's nonsensical, but illustrates the point. In this case, if you do for example A myA; myA = someOtherA; you're executing the default constructor, which does a metric ton of work, only to then throw away that work by assigning via the = operator. If instead you do A myA(someOtherA); it uses the copy constructor, which simply assigns the m_data value of the object using m_data of someOtherA. Even if you don't explicitly define a copy constructor, C++ will create one for you (called the implicitly defined copy constructor), that simply copies the value of each member variable over using their own copy constructor. There's a pitfall here, because if the member variables of a class are complex types themselves, they may have time intensive copy constructors that are invoked by the implicitly generated copy constructor of your class without you noticing.
Join our real-time social learning platform and learn together with your friends!