C++ problem (one last try)

Patrick Head patrick at phead.net
Sun Aug 8 00:49:56 PDT 2004


On Sun, 2004-08-08 at 00:40, michael wrote:
> error: incompatible types in assignment of `char*' to `char[20]'  on line  
> 7.As far as i can see,i'm assigning char* to char*,or?As always please  
> don't bother if this seems excessive,and thanks again!
> 
> 
> #include<iostream>
> using namespace std;
> class car
> {public:
> car();
> char itsName[20];
> car(char a[20]){itsName=a;} //line 7
> };
> 
> int main()
> {car c("citroen");
> 
> cout<<c.itsName;
> return 0;
> }

Michael,

The compiler IS acting correctly in this code example.  When you
declared your class, you said to the compiler, "every time you create a
new object of type car(), set aside 20 characters of space in memory
called itsName.  Then the constructor you coded said that it would
accept a char * named a (even though you indicated its length, the C and
C++ languages do NOT by default allow passing of data between functions
by what is called "reference".  They ALWAYS (without special syntax in
C++) pass by "value".  In other words, the only way to pass the data
contained in any array to another function, is to pass it's address in
memory.  So, long story short, you are still trying to use a char *
(memory address) as a value to assign to an array, which is NOT allowed
in C.

As mentioned earlier, you should code the constructor with a char * as
its argument, then use strcpy to copy all the data from the function
argument to the actual storage array in the object.

Hope this helps!

Patrick

-- 
Patrick Head
patrick at phead.net





More information about the lfs-chat mailing list