C++ classes getting value using pointers and strcp

2019-09-21 15:26发布

问题:

I am trying to understand C++. Can anybody explain what this code does exactly, I understood that it is some type of setter and getter in Java but I am not sure.

Comm::Comm(const char* id)
{
strcpy(this->id, id);
}


char* Comm::getId()
{
   return id;
}

回答1:

What does this code do?

It burns the eyes of children.

The assumption here is that the class Comm has a member variable of type char* or char[N]. There is no "setter" per se, but Comm's constructor attempts to copy its input to that member variable. The getId function is a getter for this member variable.

Depending on the rest of the code, this could be totally flawed due to lack of memory allocation, lack of memory de-allocation, and lack of copy semantics. At best the member is an array and then the lack of range checking in the strcpy call is a serious security risk.

The class would be much better redesigned with the use of std::string.

I would not encourage you to learn from this code snippet.

Instead, learn from a good book.