C++ examples for Class:Constructor
Create a copy constructor
#include <iostream> #include <iomanip> using namespace std; // declaration section class Complex/* www . j ava 2s . 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; }