tags:

views:

249

answers:

4

In C++, you have to be explicit about many things, like using delete. This gives the programmer more options, but, it doesn't always make sense to me. For example: initializing an array of characters in the constructor. Why aren't simple tasks like these can be handled easier than this way:

class x{
enum {Lim =20};
char a[Lim];

x(const char* s){
strncpy(a, s, Lim - 1);
a[Lim - 1] = '\0';
}
}

In, C#, all you have to do is:

class loai { 
public char[] a;
public loai(char[] a) {
    this.a = a;
}
}

P.S: Sorry for yesterday. I was tired and couldn't express my ideas well. Thanks

+5  A: 

You can initialize an array of characters....

char a[] = "hello";
Brian R. Bondy
why the down vote?
Brian R. Bondy
Because that's not what I was talking about.
Loai Najati
Well you specifically asked why it was not possible to initialize an array of characters.... Seems to me like that is exactly what you asked. I do understand though that you were looking for a more generalized answer, but I think there are only specific answers to your specific questions (Whatever they may be).
Brian R. Bondy
The question wasn't clear, but I interpreted it as a character array non-static data member, for which this answer wouldn't apply.
Roger Pate
@Roger Pate: `a` is not a pointer to a static memory block, it is an array on the stack and it is initialized; therefore, yes this answer does apply.
Brian R. Bondy
Brian: `struct A { char a[20]; };`, A::a is a non-static data member. Your answer doesn't apply to this case. The question wasn't clear.
Roger Pate
@Roger Pate: Ya he could have meant that too.
Brian R. Bondy
+2  A: 
Roger Pate
A: 

Since you've tagged your question as C++, consider following:

class x
{
public:
    explicit x(const std::string &str)
        : str_(str)
    {}

    explicit x(const char *str)
        : str_(str ? str : "")
    {}

    ~x() {}

private:
    std::string str_;
};

Don't see how C++ would make me be too explicit in any way. Yes, std::string is not exactly an array of characters, but, ask yourself, do you really need it? I wouldn't expect std::string to perform considerably worse than a char array in probably 99% of possible use cases. So, don't make your life complicated, use the good things that C++ provides you, not the things left for C compatibility, unless you absolutely need to and know what you're doing.

EDIT: Ah, I see, the explicit keyword adds "explicitness" to C++ :) Keep forgetting it on a first round of typing.

Dmitry
A: 

Here's a simpler C++ version, which looks almost exactly like your C# sample:

class loai { 
public:
  std::vector<char> a;
  loai(const std::vector<char>& a) : a(a) {}
};

Of course you can make everything awfully complicated by using the wrong datatypes, regardless of language. In C++, plain arrays are very simple types, and so in many cases, something like std::vector is more convenient to use.

jalf