-1

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,615
  • 3
  • 26
  • 53

2 Answers2

8

sure:

#include <string>

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

};

Balog Pal
  • 15,325
  • 2
  • 22
  • 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
  • 17,620
  • 1
  • 35
  • 63