Home‎ > ‎CS 11M‎ > ‎

Special Member Functions

Introduction 

So far we've learned about member functions, including constructors and destructors and member data. Today we'll see how special member functions can improve the behaviors of our classes. 

Copy Constructors

A special  constructor is called when you want to copy one instance of your class into another instance. This is the case when you have code like this: 

Color a; 
Color b = a; 

In the code above the copy constructor for Color is called. The copy constructor looks like this: 

class Color {

  public:
    // Copy constructor
    Color(const Color &other) {
      cout << "Copy constructor!" << endl;
      red = other.red; 
      green = other.green;
      blue = other.blue;
    }
   ...   
}; 

The copy constructor controls how a copy is made of your class. C++ provides a default copy constructor which simply copies all data member using the assignment operator. For our Color class this is sufficient. 

Operator Overloading

What if you wanted to add two colors like this:

Color a;
Color b; 
Color c; 
c = a + b; 

That's illegal until you add a special member function that allows you to add two instances of your class: 

  const Color operator+(const Color &other) {
      Color newColor; 
      newColor.red = red + other.red; 
      newColor.green = green + other.green;
      newColor.blue = blue + other.blue;
      return newColor;
    }

You can also add things of different types. What if you wanted to be able to add a number to all three color values like this:

Color a; 
a = a + 10; 

This member function allows you to add an integer to a color: 

    const Color operator+(const int &amount) {
      Color newColor;
      newColor.red = red + amount;
      newColor.green = green + amount;
      newColor.blue = blue + amount;
      return newColor;
    }

You can overload all of the arithmetic operators in C++ making your classes very flexible and easy to use. 

Pretty Printing

You've probably noticed that this doesn't work with your color class: 

Color myColor(12, 45, 56); 
cout << "My color is: " << myColor << endl;

If you want to create a "pretty print" function that make cout of your class possible (and useful) you should overload the << operator like this:

ostream &operator<<(ostream &os, const Color &c) {
  os << "color(r:" << c.red << ", g:" << c.green << ", b:" << c.blue << ")";
  return os;
}

The operator<< function is NOT a member function. So, if you want it to be able to access the internal variables in Color you have to place this line inside your Color class:

  friend ostream &operator<<(ostream &os, const Color &c);

That makes the function a friend of the class. Friend functions have access to private members. 

Comments