Click here to Skip to main content
15,888,802 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
	int x;
	int y;
public:
	A()
	{
		cout << "Inside default constructor\n" << endl;
		x = 99;
		y = 100;
	}
	void show_data();
	A(A&);
};
A::A(A &temp)
{
	cout << "Inside Copy constructor" << endl;
	x = temp.x;
	y = temp.y;
}
void A::show_data()
{
	cout << x << ' ' << y << endl;
}
int main()
{
	class A a1, b1(a1);
	b1.show_data();
    return 0;
}


Below code throws error:-

// ConsoleApplication81.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
	int x;
	int y;
public:
	A()
	{
		cout << "Inside default constructor\n" << endl;
		x = 99;
		y = 100;
	}
	void show_data();
	A(A);
};
A::A(A temp)
{
	cout << "Inside Copy constructor" << endl;
	x = temp.x;
	y = temp.y;
}
void A::show_data()
{
	cout << x << ' ' << y << endl;
}
int main()
{
	class A a1, b1(a1);
	b1.show_data();
    return 0;
}


error that i am getting is:-

copy constructor for class "A" may not have a parameter of type "A"

What I have tried:

I have created my own copy constructor like below using argument as reference type and it works fine.but if i am trying with non-reference type then it is throwing an error.Just trying to understand why is it so.
Posted
Updated 26-Jul-21 22:39pm
v3
Comments
OriginalGriff 27-Jul-21 3:36am    
What error?
Where?
What have you tried to fix it?
Shujaul Hind 27-Jul-21 4:28am    
question updated please check

Because the rules of the language state that the copy constructor requires a reference item: Copy constructors - cppreference.com[^].
 
Share this answer
 
Comments
Shujaul Hind 27-Jul-21 4:25am    
@Richard you are right but i want to know the reason behind this rule
Richard MacCutchan 27-Jul-21 4:37am    
Because without the reference operator the code will pass a copy of the complete object (like a value) in the call, not just a pointer to it.
Hypothetical copy constructor with non-reference type, such as
A(A);

requires the copy of its argument. Well, how class instances are passed by value in C++? Using copy constructor. What copy constructor? Obviously, not the same one, this creates an endless recursion.

Standard requires copy constructor with const reference, which gives the desired effect (parameter is read-only), gives a good performance and doesn't contain logical problems as mentioned above.
 
Share this answer
 
Comments
Shujaul Hind 27-Jul-21 5:07am    
Thanks a lot i got it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900