Click here to Skip to main content
15,895,922 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Programmers,

I would like to know why only reference is used in copy constructor, why not pointer?

I used pointer, I get perfect result.

Please put some light on this. Below is the code that I wrote, I am able to see expected result. The same result I get when use reference.

Is there any specific reason not to use pointer?

C++
#include "stdafx.h"
#include<iostream>
#include<stdio.h>

using namespace std;

class MyString
{
  public:
  char *str1;
  int i;
  MyString(char * , int );
  MyString();
  MyString (MyString* );
};

MyString::MyString()
{


}

MyString::MyString( char * str2, int j)
{

   str1 = str2;
   i= j;

}

MyString::MyString (MyString * obj3)
{

   int len = strlen(obj3->str1);

   str1 =  (char*)malloc(len +1);
  strcpy( str1, obj3->str1); 
  i= obj3->i;

}

int _tmain(int argc, _TCHAR* argv[])
{
	 MyString obj1("HelloWorld", 10);

 MyString obj2(&obj1);

  cout<<obj2.str1;
  cout<<obj2.i;

  int j;
  cin >>j;

	return 0;
}}



Regards,
Joy
Posted
Updated 5-Jun-14 21:55pm
v2

You question could be rephrased this way: "why should we use references instead of pointers?"
You may find a reason here: "[8.6] When should I use references, and when should I use pointers?"[^].

Please note this
C++
MyString (MyString* );

should be instead
C++
MyString (const MyString* );
 
Share this answer
 
Comments
[no name] 6-Jun-14 4:21am    
Agree, 5ed.
Best answer, in my opinion -

"A null pointer wouldn't make sense. And using a pointer wouldn't allow copying temporaries, so you couldn't do things like:

MyClass
func()
{
    //  ...
    return MyClass(...);
}
 
Share this answer
 
That's how the copy constructor is defined. The constructor you defined is, per definition, not a copy constructor at all. The copy constructor is the one that will be implicitely called whenever you pass an argument by value to a function. Since it's implicit, you can't specify to take the address of the original object.

You're free to define a constructor that takes a pointer instead and make it behave the same. But that is not the one that will be called implicitely.
 
Share this answer
 

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