This post has already been read 1620 times!

C++ Copy Constructor passed by value or by reference ?

Sollution

The parameter in the copy constructor A(A other) is an instance of type A.
When the copy constructor is executed, it calls the copy constructor itself because of the pass-by-value parameter.
Since endless recursive calls cause call stack overflow, a pass-by-value parameter is not allowed in the C++ standard,and both Visual Studio and GCC report an error during compiling time.

We have to modify the constructor as A(const A& other) to fix this problem. That is to say, the parameter in a copy constructor should be passed by a reference.

Source Code in C++


#include "stdio.h"
#include "stdlib.h"
#include "iostream"

using namespace std;

class A {
	private:
		int value;

	public :
		A (int n){
			value = n;
		}

		//  the parameter in a copy constructor should be passed by a reference
		A (const A &other)
		{
			value = other.value;
		}

		void Print()
		{
			cout << value << endl;
		}
};

int main()
{
	A a = 10;
	A b = a;

	b.Print();

	return 0;
}

Comments are closed.

Post Navigation