The easiest and most reliable method is to simply use a convert constructor:
class Rectangle
{
public:
Rectangle(uint8_t l, uint8_t h) : length(l), height(h) {};
// ...
};
This should be your go-to method until for whatever reason this is impossible.
Barring this, the next best thing to do is simply do a memberwise initialization:
Rectangle rect;
rect.width = 20;
rect.height = 40;
If it becomes impossible to do the above, and iff the object in question is what the Standard refers to as an "aggregate" (basically a POD), you can use an initializer like this:
Recatagle rect = {10,20};
When doing this, you must bear in mind that the members will be initialized in the order in which they are declared in the class. If you change the order of declaration, you will break every initialization like the above. This is very brittle. For this reason, I limit my use of a construct like this to cases where the class in question is highly localized (like a helper class in a single translation unit), and I document the need to keep the order of declaration intact.
EDIT PER COMMENTS:
In the instance you are trying to copy strings in to your class, or pointers to any sort of data, you will need to do a deep copy:
class Gizmo
{
public:
Gizmo(const char* str) : str_(0)
{
str_ = new char[strlen(str)+1];
strcpy(str_,str);
}
};
Note the clumsiness and how brittle the above code is. There are plenty of things that could go wrong here. Not the least of which are forgetting to delete
str_
when Gizmo
is destroyed, the ugliness and seeming lack of necessity for new
ing a char
string in the first place, one-past-the-end errors ... the list goes on. For these reasons, it's best to avoid using raw pointers at all and using either smart pointers (ie unique_ptr
, shared_ptr
, etc) or collection classes. In this case, I'd use a std::string
, which can be thought of as a collection class:
class Gizmo
{
public:
Gizmo(const char* str) : str_(str) {};
private:
std::string str_;
};
Feel free to convert this for use with a u_char*
, and to add robustness by means of verifying the source pointer is valid.