I’m writing a C++ class for a book that contains a name:
class Book {
private:
char* nm;
..........
............
..........
...........
};
I am not allowed to use std::string in this assignment. So here I am using strdup to copy the value of the parameter name into nm in the constructor:
Book::Book(const char *name, int thickness, int weight)
: nm(NULL)
, thck(thickness)
, wght(weight)
{
if (name)
nm = strdup(name);
}
Is there an alternative of achieving the same result without using strdup, but using the keyword new instead?
Strictly speaking: The
stringclass is part of the Strings library. This is much easier to use, dynamic in nature and you have less worry when copying/assigning than C-style strings.The other approach is to manually copy out:
The problem with this approach is that you will have to manage the memory yourself and implement all the Big-three special member functions yourself (and ensure exception-safety as much as you can).