C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Copy Constructors

By David Bolton, About.com

10 of 10

Summing up Constructors and Assignment Operators

POD Revisited

POD (Plain Old Data) is more or less data that can be copied safely byte by byte and is usually taken as meaning elements in C++ that are compatible with C.

POD types include

  • All of the int types. (char, short, int and long and signed/unsigned versions)
  • All of the float types (float and double)
  • bool
  • Enumerate types (enums)
  • Pointers to const values
  • Pointers to static members.
  • Structs and unions that contain POD data.
POD data can be copied with memcpy or initialized to zero with memset functions. Non POD data requires a constructor to initialize it, but POD data requires explicit initialization.

If the data is POD (Plain Old Data) then you don't need a copy constructor. For non POD data though

  • Always implement a base class copy constructor.
  • Call the base class copy constructor in the derived class initializer list.
For Assignment Operators
If the data is POD then the compiler supplied assignment operator will copy all of the data for you, even in class hierarchies. But if the member data isn't POD or you supply your own derived class assignment operator then you must call a base class assignment operator. This can be one you have written or if the base class is POD then the compiler supplied one will do.

It can take a while for all this to sink in fully. I found that I learnt best by considering all of the different situations with POD and non POD and trying out copying and assigning objects. Example 1 is handy for that.

Preventing Copying and Assignment

Sometimes you don't want an object to be able to be created by copying or even assignment. E.g. a singleton class where only one instance can exist. Just implement a copy constructor and/or assignment operator behind a protected: directive.

That completes this lesson. The next one will be about static data and functions in classes.

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Summing up Constructors and Assignment Operators

©2009 About.com, a part of The New York Times Company.

All rights reserved.