• 0

C++ Copy constructor help


Question

Hi. I have a pretty simple class called patients and I need to create a copy constructor. For example if I have 2 patients eg. P1 and P2 and I wanted to assign the contents of P2 into P1 eg P1 = P2; something like that how would my copy constructor look like? I have never created one before and I need advice. I just want to assign the private members of P2, such as patient number, priority, etc.. to P1. Here is my patients class. It is actually simpler since most of the functions are just gets and sets.

class Patient
{

private:
	int itsPatientNumber;
	int itsPriority;
	int itsTime;
	int itsMisdiagnose;

public:

	Patient ();
	~Patient ();
	void setPriority (int priority);
	int getPriority ();
	void setTime (int time);
	int getTime ();
	void setMisdiagnose (int misdiagnose);
	int getMisdiagnose ();
	void setPatientNumber (int patientNumber);
	int getPatientNumber ();

	bool operator < (const Patient &P) const
	{
  if (itsPriority < P.itsPriority)
 	 return true;
  else if (itsPriority > P.itsPriority)
 	 return false;
  else if (itsTime < P.itsTime)
 	 return false;
  else 
 	 return true;
	}

};

Patient::Patient ()
{
	itsPriority = itsTime = itsMisdiagnose, itsPatientNumber = 0;
}


Patient::~Patient ()
{
}

void Patient::setPriority (int priority)
{
	itsPriority = priority;
}

int Patient::getPriority()
{
	return itsPriority;
}

void Patient::setTime (int time)
{
	itsTime = time;
}

int Patient::getTime ()
{
	return itsTime;
}

void Patient::setMisdiagnose (int misdiagnose)
{
	itsMisdiagnose = misdiagnose;
}

int Patient::getMisdiagnose ()
{
	return itsMisdiagnose;
}

void Patient::setPatientNumber (int patientNumber)
{
	itsPatientNumber = patientNumber;
}

int Patient::getPatientNumber ()
{
	return itsPatientNumber;
}

Thanks!

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

For this class you don't really need a copy constructor as you don't have any special copy cases (such as a pointer member). The default one generated by the compiler will suffice.

However if you still wanted to know how it was done:

declaration:

Patient (const Patient& pThat);

definition:

Patient::Patient (const Patient& pThat)
{
    itsPatientNumber = pThat.itsPatientNumber;
    itsPriority      = pThat.itsPriority;
    itsTime          = pThat.itsTime;
    itsMisdiagnose   = pThat.itsMisdiagnose;
}

hope that helps,

bwx

Link to comment
Share on other sites

  • 0
Why don't you have to overload the '=' operator to say P1 = P2? Can't you only do P1(P2)? Thats the way they learned us in school anyway...

That is automatically generated by the compiler aswell; it acts just like a copy constructor.

Patient& operator = (const Patient& pThat);

bwx

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.