A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing


  • 4 years ago

In C++, what is the difference between something like: int i = 3; and int i(3); and which is better?

  • This Question is Closed
  1. anonymous
    • 4 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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.

  2. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...


  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.