Question:
C++ copy constructor with an array and a for loop?
Tala
2012-06-22 22:16:25 UTC
hi , i have an assignment with class rectangle saying i should create an array of 250 rectangles , and make each of the 250 rectangles a copy of an other rectangle object i created previously named R3

i am not sure what to put in the for loop ?
should i use a get function or something ?


This is the complete program

#include

class Rectangle
{
private:
float width ,hight;
public:
Rectangle()
{
width=0;
hight=0;
display();}
Rectangle(float w,float h)
{
if ((h<0.0) && (w<0.0))
{
width=w;
hight=h;
display();
}
else cout<<"0";
}

Rectangle(Rectangle & x)
{
width= x.width;
hight= x.hight;
if ((hight<0.0) && (width<0.0))
{display();
}
else cout<<"0";
}

void setwidth (float w)
{
if (w<0.0)
{ width=w;
}
else cout<<"0";
}


void sethight (float h)
{if (h<0.0)
{ hight=h;
}
else cout<<"0";
}

float computeArea()
{
float Area;
Area = width*hight;
return Area ; }

bool isSquare ()
{
if(hight==width)
return true;}

void display ()
{ cout<<"width="<
};


void main ()
{
Rectangle R1 (3.25 , 3.25);
Rectangle R2 (4.5 , 2.5);
Rectangle R3 (R1);
Rectangle Arr[250];

for(int i=0; i<250 ; i++)
{ Arr[i] =????????????

}

}
Three answers:
MichaelInScarborough
2012-06-22 23:34:56 UTC
Hi Tala,

As 007 mentioned, assigning R1, R2, or R3 to the array elements is definitely something you could do.



While reading your code I was not sure, whether you wanted to check parameters for width and height (hight) to be less than 0 rather than greater than zero. This check applies to your parametrized constructor, to the copy constructor, to the setwidth and sethight methods of your Rectangle class.

I would suggest that the condition for a valid rectangle would be ((width > 0.0f) && (hight > 0.0f))



I hope this is helpful feedback.
modulo_function
2012-06-23 06:41:25 UTC
I copied and pasted your program into my CodeBlocks and you have many logic errors.



Those ifs in the constructors are in the wrong direction and will set the width and hight to 0. That's not what you want.



In

Rectangle(float w,float h)

change

if ((h<0.0) && (w<0.0))

to

if( h>0.0 && w>0.0 )



Your copy constructor works just fine. Use this statement in your main:

for(int i=0; i<250 ; i++)

Arr[i] =Rectangle(R2);



that will make every Arr[] rectangle a copy of R2.
James Bond
2012-06-23 05:43:31 UTC
Arr[i] =R1; //R2 or R3


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...