Quick Answer:
It depends on what do you want to achieve.
Long, Extended, Boring Answer:
You hit the nail.
I usually dislike that "C++" allows "Struct (s)" allows to declare methods. Preferably, I use explicit "Class (es)" for methods required and P.O.D. "Struct (s)" for only fields.
Yet, I agree that some basic simple operations, like:
- assign initial values ("constructor")
- make a copy of a structure ("copy constructor)
- assign values to an existing structure ("overload assign operator")
Are required, and, in those circumstances, methods for structures, make sense.
Suggestion
Another potential solution is to use P.O.D. structures, but, still conceptually treat them as classes and objects.
Wrap those declarations in a namespace, and, add global functions, for the most important actions.
The code declaration could be similar to this:
namespace Customers
{
struct CustomerStruct
{
char[255] FirstName;
char[255] LastName;
int Age;
bool IsAlive;
bool IsMarried;
}; // struct
CustomerStruct* CreateCustomer
(
char* NewFirstName;
char* NewLastName;
int NewAge;
bool NewIsAlive;
bool NewIsMarried;
)
{
CustomerStruct* NewCustomer = new CustomerStruct();
NewCustomer->FirstName = NewFirstName;
NewCustomer->LastName = NewLastName;
NewCustomer->Age = NewAge;
NewCustomer->IsAlive = NewIsAlive;
NewCustomer->IsMarried = NewIsMarried;
return NewCustomer;
} // CustomerStruct* CreateCustomer (...)
} // namespace
The code that applies the solution, could be something like this:
#include <Customers>
using Customers;
int main (...)
{
int ErrorCode = 0;
CustomerClass* ThisCustomer =
Customers::CreateCustomer
("John", "Doe", 23, true, true);
// do something with "ThisCustomer"
delete ThisCustomer;
return ErrorCode;
} // int main(...)
This alternative approach is better when a huge memory allocation of data is required, or interacting with other low-level shared libraries.
This approach, with some changes, is applied in Game Development.
Extra
Personally, I consider a syntax extension for "C++", or even, a new "C++" based P.L. that solves this issue:
// "Plain Old Data" Structure
// No Methods, No "Functors", allowed
strict struct CustomerStruct
{
char[255] FirstName;
char[255] LastName;
int Age;
bool IsAlive;
bool IsMarried;
}; // strict struct
// Object Oriented "Plain Old Data" Structure
// Yes, Methods and "Functors" allowed
relaxed struct CustomerStruct
{
char[255] FirstName;
char[255] LastName;
int Age;
bool IsAlive;
bool IsMarried;
public void Foo();
public void Bar();
public (void*) (SomeFunctor) ();
}; // relaxed struct
// Class and Object Oriented
class CustomerClass
{
public char[255] FirstName;
public char[255] LastName;
public int Age;
public bool IsAlive;
public bool IsMarried;
public void Foo();
public void Bar();
}; // class
Cheers.
struct
andclass
is that one defaults to private and the other to public.