more C++ (previously sent without a title,sorry)

Björn Lindberg d95-bli at
Wed Aug 11 04:50:05 PDT 2004

michael <michael8110 at> writes:

> From: michael <michael8110 at>
> Glad to see you are making heads and tails of all this!!  It's very nice
> to see someone so dedicated to learning a language, and doing it by
> testing and discussion.
> It is likewise very nice to get so much support from all of you,thanks
> very much again!
> Sooo,finally you've admitted it!
>   " For char pointers, which
> ar[3] ends up being, the language itself knows to actually output the
> string it points to."
> So the simple question remains(and that,Björn,is the point)
> why does g++ applied to the following
> #include<iostream>
> using namespace std;
> class car
> {public:
> char itsName[20];
> car(char a[20]){itsName=a;}
> };
> int main()
> {car c("citroen");
> cout<<c.itsName;
> return 0;
> }
> return
> test7.cpp: In constructor `car::car(char*)':
> test7.cpp:6: error: incompatible types in assignment of `char*' to
> `char[20]'
> after all doesn't "the language know" that when it sees a char* it's
> the  string the poor devil means?
> I mean,if i do
> char a[20]="citroen";
> cout<<a;
> i'll get the string as seen above...

That is because, like I said in an eralier ost, the language doesn't
"know" that it is a "string". The reason cout does the right thing for
a variety of types is (like I have said before), it is overloaded with
a multitude of different functions taking values of different
types. More specifically, it has an overloaded function for the type
'char *', which will try to print an array of characters at that
position. For other pointers in general, it will instead print the
pointer address. There is no magic involved, and no special
"knowledge" on the part of the compiler. In fact, you could define
your own output stream, overload the << operator to achieve the same
thing. Another thing is that you yourself can extend the output
functionality of cout (or output streams in general):

std::ostream & operator<<(std::ostream & os, const car & c)
    os << "A car by the name of " << c.itsName;
    return os;

int main()
    car c("citroën");
    std::cout << c << '\n';
    return 0;

... voilà, direct output of cars!

> so why can't the constructor
> (car(char  a[20]){itsName=a;} )do the same,

Because it is not allowed. You cannot copy arrays by assigning to
them. That is just how it is.

> since it
> already admits itsName by itself stands for a char[20]?Either both a
> and  itsName are char* or char[20].

You cannot assign to an arry. It's gibberish. Either you assign to the
elements of an array, or you use pointers.


More information about the lfs-chat mailing list