Home Articles Books Downloads FAQs Tips

What's Wrong With This Code? Volume #5


Copy constructors
by Chris Uzdavinis

A programmer has written a base class and a derived class, and instantiated an object of that derived class, called d1. Later, another Derived object is needed, a copy of d1. Here is the code.

#include <iostream>
using std::cout;
using std::endl;

class Base
{
public:
  Base()                                    { cout << "1" << endl;}
  Base(Base const & rhs)                    { cout << "2" << endl;}
  virtual ~Base()                           { cout << "3" << endl;}
};


class Derived : public Base
{
public:
  Derived() : x_(0)                         { cout << "4" << endl;}
  Derived(int x) : x_(x)                    { cout << "5" << endl;}
  Derived(Derived const & rhs) : x_(rhs.x_) { cout << "6" << endl;}
  ~Derived() { }

  int get_x() const { return x_; }
private:
  int x_;
};


main()
{
  Derived d1(999);
  // copy construct d2 from d1
  Derived d2(d1);
}

What is the output of this program? Is it surprising? What needs to be done to make it act like the programmer had probably expected?


Answer


Code for this edition
wwwtc5.zip BCB4 project that contains problem code.
wwwtc5x.zip Same project, includes an EXE (55 kb).


Copyright © 1997-2002 by Harold Howe.
All rights reserved.