C++ Constructor copy constructor

Description

C++ Constructor copy constructor

 
#include <iostream>
#include <iomanip>
using namespace std;
// declaration section
class Complex//w  w  w .j  a  va  2  s. c  o  m
{
   private:
   double realPart;       // declare realPart as a double variable
   double imaginaryPart;   // declare imaginaryPart as a double variable
   public:
   Complex(double real = 0.0, double imag = 0.0)  // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
   Complex(const Complex&);      // copy constructor
   void showComplexValues();     // accessor prototype
   void assignNewValues(double real, double imag);  // inline mutator
};   // end of class declaration
// implementation section
Complex::Complex(const Complex& existingNumber)  // copy constructor
{
   realPart = existingNumber.realPart;
   imaginaryPart = existingNumber.imaginaryPart;
}
void Complex::showComplexValues()  // accessor
{
   char sign = '+';
   if (imaginaryPart < 0) sign = '-';
   cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i';
}
int main()
{
   Complex a(2.3, 10.5), b(6.3, 19.2);  // use the constructor
   Complex c(a);    // use the copy constructor
   Complex d = b;   // use the copy constructor
   cout << "Complex number a is ";
   a.showComplexValues();
   cout << "\nComplex number b is ";
   b.showComplexValues();
   cout << "\nComplex number c is ";
   c.showComplexValues();
   cout << "\nComplex number d is ";
   d.showComplexValues();
   return 0;
}

The copy constructor must accept an argument of the same class type and create a duplicate for the class.

A copy constructor should be defined with a const reference parameter, so for the Pool class it looks like this:

 
class Pool//from   w w  w . j a  v a 2  s. com
{
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};
 
public:
  // Constructors
  Pool(double lv, double wv, double hv);
  Pool(const Pool& pool);
  Pool(double side);                         // Constructor for a cube
  Pool() {}                                  // No-arg constructor
 
  double volume();                          // Function to calculate the volume of a pool
};
 
Pool::Pool(const Pool& pool) : length {pool.length}, width {pool.width}, height {pool.height} {}
 

The form of the copy constructor is the same for any class:

 
Type::Type(const Type& object)
{
  // Code to duplicate of object...
}



PreviousNext

Related