1. Computing

C++ Tutorial - Copy Constructors

By

1 of 10

A Reminder about Constructors
In this lesson, I'll be looking in depth at constructors, default constructors, and copy constructors plus related topics. This gets a bit more complex than stuff we've seen before. Lets remind ourselves about constructors.

In C++ a constructor is a function with the same name as the class. Its purpose is to

  • Create a new instance of the class
  • Initialize the member data of the instance

Default Constructors

If you have written a constructor for your class then when you create an instance of it, the constructor is automatically called. If you haven't supplied a constructor, then the compiler will create a default one for you. This default constructor takes no parameters, or has default values for all parameters. A default parameter is one where the parameter value is supplied in the definition. For example in the class aclassname
 aclassname(int param=5) { 
   value = param
 }
 
The 5 is the default value parameter. It means that the constructor can be called as
 aclassname fred
 
and the value 5 is passed in, or 7 below
 aclassname fred(7) // overrides the default 5
 
Here's a longer example.

 class phonerec {
     public:
     string name;
     string phonenumber[16];
     phonerec(string myname ="Me",string myphone="555-1000") ; // defaults
 };
 
 phonerec p; // calls the constructor a default parameter "Me"
 phonerec p("David","0207 384") ;
 
You can of course write your own default constructor. You only get a default constructor supplied for free if you haven't written any kind of constructor. If you create one with non defaulted parameters and the compiler needs a default constructor, it will generate an error. It also doesn't like multiple default constructors as it has no way to tell which to use.

On the next page : Initializing Default Constructors

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. C++ Tutorial - Copy Constructors

©2014 About.com. All rights reserved.