Copy Constructor

C++ Programming

C++ Programming Examples

/* Power Calculation */
#include<iostream>
using namespace std;

class power {
	int val, number;
	public:

		/* Constructor */
		power(int no) {
			number = no;
			val = number * number;
			cout << "Square of " << number << " is " << val << endl;
		}

		/* Copy constructor */
		power(const power & a) {
			val = a.val * a.number;
			cout << "Cube of " << a.number << " is " << val << endl;
		}

};

int main() {
	int no;
	cout << "Enter a number to perform Square and Cube:" << endl;
	cin >> no;

	/* Object 'square' created and initialized */
	power square(no);

	/* Copy constructor called */
	power cube(square);
	return 0;
}


          /****** Output ******/
          

Enter a number to perform Square and Cube:


2


Square of 2 is 4


Cube of 2 is 8

Learn more about Copy Constructor in C++