Hello all,
I have an issue with constructors...
I've put up the first code snippet here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Animal
{
private:
char _name[0x100];
public:
Animal(char* name);
};
Animal::Animal(char* name)
{
strncpy(_name, name, sizeof(_name));
}
int main(void)
{
Animal x("cat");
Animal y(x);
return 0;
}
| |
First: I don't understand how the line "Animal y(x);" can compile since I did not provide a constructor that take an Animal object as parameter; however, it does compile and seems to have the same effect as "Animal y = x" (members copy).
Then, I decide to add a cast operator like:
1 2 3 4
|
Animal::operator const char*()
{
return _name;
}
| |
And compile the same code. I was thinking: ok now, the line Animal y(x) should call the Animal(char*) constructor. But no... doesn't change anything.
I now add another constructor:
1 2 3 4
|
Animal::Animal(Animal& x)
{
strncpy(_name, x._name, sizeof(_name));
}
| |
And this time, the line "Animal y(y)" indeed calls it...
Someone could explain this? It's fairly misleading that the line Animal y(x) compiled under all circumstances., especially if the class points to dynamically-allocated data...
Thanks!