THE COPY CONSTRUCTOR IN A DERIVED CLASS
Remember that the copy constructor is called automatically when you declare an object that is initialized with an object of the same class. Look at these statements:
CBox myBox(2.0, 3.0, 4.0); // Calls constructor
CBox copyBox(myBox); // Calls copy constructor
The first statement calls the constructor that accepts three arguments of type double, and the second calls the copy constructor. If you don’t supply your own copy constructor, the compiler supplies one that copies the initializing object, member by member, to the corresponding members of the new object. So that you can see what is going on during execution, you can add your own version of a copy constructor to the CBox class. You can then use this class as a base for defining the CCandyBox class:
// Box.h in Ex9_05
#pragma once
#include <iostream>
using std::cout;
using std::endl;
class CBox // Base class definition
{
public:
// Base class constructor
explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0):
m_Length(lv), m_Width(wv), m_Height(hv)
{ std::cout << std::endl << "CBox constructor called"; }
// Copy constructor
CBox(const CBox& initB)
{
std::cout << std::endl << "CBox copy constructor called";
m_Length = initB.m_Length;
m_Width = initB.m_Width;
m_Height = initB.m_Height;
}
// CBox destructor - just to track calls
~CBox()
{ std::cout << "CBox destructor called" << std::endl; }
protected:
double m_Length;
double m_Width;
double m_Height;
};
Don’t forget that a copy ...
Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.