Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use of default constructor over assignment operator

Status
Not open for further replies.

srk24

Programmer
May 6, 2012
1
CA
Hi all,

Could some one please tell me what is the advantage of Default constructor over default assingment operator.
Is there something that can be accomplished only by constructor?

Regards,
Srk
 
For example
Code:
int counter;
class Simple
{
public:
   Simple ()
   :  m_counter(counter)
   ,  m_lemon(0)
   {
   }
   Simple (const Simple& that)
   :   m_counter(that.m_counter)
   ,   m_lemon (that.m_lemon)
   {
   }
   Simple& operator =(const Simple& that)
   {
      // m_counter cannot be initialized here
      this->m_lemon = that.m_lemon;
      return *this;
   }
private:
   int& m_counter;
   int  m_lemon;
};
 
>what is the advantage of Default constructor over default assingment operator...
What's the advantage of motor plants over automobile sales centres?

You need contructors to create class objects from the scratch.
You need assignment operators to assign existent (created by constructors) objects.

In particular you need default constructor (not assignment operator) to define arrays of class objects (and STL containers too).

An example of a class which can't have correct assignment operator w/o a proper default constructor (othewise you can't declare arrays of this class objects or it's possible to create never-to-assign objects):
Code:
class WithDynArray
{
public:

private:
  double* pData_; // Pointer to dynamic memory chunk
  size_t  dSize_; // This chunk number of elements
};
...
WithDynArray donttreadonme;
...
Let's suppose that WithDynArray has not default constructor. Well, the donttreadonme.pData_ member is not initialized (has garbage value - pointer to nowhere). You can't assign any WithDynArray value to this variable! An assignment operator must deallocate old (target) pData memory chunk but this pointer is undefined in donttreadonme!

Add default constructor:
Code:
...
WithDynArray(): pData_(0), dSize_(0) {}
...
That's OK: now you have a good object donttreadonme (don't forget to change its name now;) and can define correct assignment operator(s) for this class.

Moral: default constructors and assignment operators are not competitors.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top