Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a constructor with that takes Strings as parameters?

I am not sure that I am using the right terminology, but question is how do I properly make a constructor that takes a string in as a parameter?

I am used to having a const char * in the constructor instead of strings.

Normally I would do something like this:

Name(const char* fName, const char* lName)
    : firstName(0), lastName(0)
{
    char * temp = new char [strlen(fName) + 1];
    strcpy_s(temp, strlen(fName) + 1, fName);
    firstName = temp;

    char * temp2 = new char [strlen(lName) + 1];
    strcpy_s(temp2, strlen(lName) + 1, lName);
    lastName = temp2;
}

What if the constructor is this:

 Name(const string fName, const string lName) { }

Do I still do base member initialization? do I still need to use string copy in the base of the constructor?

like image 749
Sarah Avatar asked Nov 05 '13 23:11

Sarah


People also ask

How do you construct a parameterized constructor?

Parameterized constructorsA parameterized constructor accepts parameters with which you can initialize the instance variables. Using parameterized constructor, you can initialize the class variables dynamically at the time of instantiating the class with distinct values.

How do you create a parameterized constructor in C++?

To create a parameterized constructor, it is needed to just add parameters as a value to the object as the way we pass a value to a function.


1 Answers

Use std::string and initializer lists:

std::string fName, lName;

Name(string fName, string lName):fName(std::move(fName)), lName(std::move(lName))
{
}

In this case, you don't need to use terribly bare pointers, you don't need allocate memory, copy characters and finally de-allocate. In addition, this new code has chances to take advantages of moving rather than copying since std::string is movable. Also it's useful to read this.

And so on....

like image 101
masoud Avatar answered Oct 06 '22 00:10

masoud