We help IT Professionals succeed at work.

c++ fundamentals question

tom419
tom419 asked
on
Medium Priority
324 Views
Last Modified: 2008-03-06
I can do this:

     double *emp;
     emp = new double(10);     //creates a ten element array on the heap, stores the address in emp

     emp[0] = 1.11111;
     emp[1] = 2.22222;
     emp[2] = 3.33333;
     emp[3] = 4.44444;

     cout<<emp[0]<<" "<<
     emp[1]<<" "<<
     emp[2]<<" "<<
     emp[3]<<endl;

With no problems, but if I try it with a struct:
     struct EmpRec {
          int ID;
          char *firstname;
          char *lastname;
     };

EmpRec *e2;
e2 = new EmpRec(10);

I get the error:
"Cannot convert int to EmpRec in function main" (I'm using the Borland 4.5 compiler).  

There must be something fundamental that I missing.  Can anyone help?

Thanks,

Tom
Comment
Watch Question

Commented:
    double *emp;
     emp = new double[10];     //creates a ten element array on the heap, stores the address in emp

     emp[0] = 1.11111;
     emp[1] = 2.22222;
     emp[2] = 3.33333;
     emp[3] = 4.44444;

     //With no problems, but if I try it with a struct:
   struct EmpRec {
         int ID;
         char *firstname;
         char *lastname;
    };

     EmpRec *e2;
     e2 = new EmpRec[10];

m.

Commented:
double *xemp;
xemp = new double(100.2);     //creates a double element and initialises to 100.2

To create array it's necessary to use [] brackets...
m.
Commented:
And
emp[0] = 1.11111;
emp[1] = 2.22222;
emp[2] = 3.33333;
emp[3] = 4.44444;
worked because C++ doesn't have checks for array size - but it rewrited memory you haven't allocated.
m.

Author

Commented:
Ok sounds good.  I can see the problem.  I actually had code for a class that I had typed in wrong, which is why I used the parens instead of the [].  So the () allow for initialization?  I didn't know that, but I can see that it works
Thanks for your help,

Tom

Author

Commented:
Very clear answer, and fast too!

Thanks!

Commented:
Hi,

when you write:
e2 = new EmpRec(10);

you are creating a new EmpRec and calling a ctor with a value of 10.

Since you do not have such a ctor, the compiler checks if there is an acceptable conversion that can be substituded.
The only available ctor is the compiler generated copy ctor which accepts an EmpRec&. This is how you get the error message (when the compiler tries to convert 10 to EmpRec).

The code:
double *emp;
emp = new double(10);
emp[0]..
emp[1]..

is actually a memory error, you are accessing unallocated memory using array notation.
As mirec wrote, the code should be:

emp = new double[10];

Udi.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.