-2

I have write this constructor to initialize the character type array

class StudentInfo
{
  char* vuId;
public:
  StudentInfo(char* vu_Id)
  {
    setVuId(vu_Id);
  }
  void setVuId(char* vu_Id)
  {
    vuId = new char[strlen(vu_Id) + 1];
    strcpy(vuId, vu_Id);
  }
};

This code is working fine. but I want to initialize without having to call setVuId function. Is there anyway to do it?

matt freake
  • 4,877
  • 4
  • 27
  • 56

2 Answers2

8

sure:

#include <string>

class StudentInfo
{
  std::string vuId;
public:
  explicit StudentInfo(const char* vu_Id) : vuId(vu_Id) {}

};

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
  • Can you explain the meaning of last line ? I know its a constructor with a pointer to const charcter parameter but what is " : vuId(vu_Id)" – Vivek Sadh Jun 24 '13 at 13:16
  • @Vivek: it passes the argument to the constructor of std::string when member vuID is constructed. google for 'c++ contsructor initialization list' for more details – Balog Pal Jun 24 '13 at 13:20
  • Hey Pal - make the constructor explicit, maybe? – doctorlove Jun 24 '13 at 14:37
0

Use std::string if you can tolerate copy-on-write and associated overhead, else use this:

#include <cstring>

class StudentInfo
{
  size_t len;
  char* data;

public:
  StudentInfo(char* vu_Id):
    len(vu_Id ? strlen(vu_Id) : 0),
    data(len ? (char*)memcpy(new char[len + 1], vu_Id, len + 1) : 0)
  {
  }

  virtual ~StudentInfo() {
    delete [] data;
  }
}
bobah
  • 18,364
  • 2
  • 37
  • 70