mercredi 28 janvier 2015

Which to use: Classes or Structs in Classes?

So, I have a bit of a philosophical question in the realm of C++11 coding best practices.


When creating an application which essentially transforms data from one system to another. Should you define everything in classes, or use structs within a class?


Here is a more concrete example of what I am referring to.


For a typical class object. Should I create it this way:



class Contact {
std::string Name;
std::string Address;
:: :: ::
void Load();
void Save();
std::string OtherFunctions( std::string Name )
}


Or is it better to separate out the data from the class:



struct ContactInfo {
std::string Name;
std::string Address;
:: :: ::
}

class Contact {
ContactInfo data;
void Load();
void Save();
std::string OtherFunctions( std::string Name )
}


Several reason that I am contemplating the Struct over just doing in a class is the ability to transfer data between APIs. For example, the creation of these objects is done at a low level pure C++ application. But, at some point through the process, it is exposed to a managed C++ application and then finally consumed in a .NET application.


Secondly, as information is passed around from function to function, I am passing only the information and not the class object. With modern compilers, perhaps this point is mute, but logically to me, it seems better to pass data only than objects.


Thirdly, it separates class members needed to manage the object data from the data itself. So having a members like ErrorCode, ErrorMessage, etc, don't pollute what is considered data and what is not.


Am I off base here? Is there a better way that I should be doing this type of activity?


Aucun commentaire:

Enregistrer un commentaire