jeudi 18 février 2021

How to design c++ class in a way to have a base attributes and add attributes for few cases

I have a basic class ContactDetails which has a private variables as string name and string address. This ContactDetails data structure is used in my program for all entities. For some entities, I need other info on top of name and address, such as phone number, pin code etc. How to design the class.

               class ContactDetails {
               private:
                     std::string name;
                     std::string address;
               public:
                      ContactDetails() {
                      this->name = "";
                      this->address = "";
                      }
                      std::string getName() { return name; }
                      std::string getAddress() { return address; }
                      void setName(std::string n) { name = n; }
                      void setAddress(std::string n) { address = n; }
               }

               class ContactDetailsHelper {
               public:
                        ContactDetails getX() {
                                    ContactDetails obj;
                                    obj.setName("X");
                                    obj.setAddress("New York");
                                    return obj;
                        }
                         ContactDetails getY() {
                                    //Y has phone number, pin code, county code etc details available.
                                    ContactDetails obj;
                                    obj.setName("Y");
                                    obj.setAddress("Chicago");
                                    //need to set more details in the object
                                    return obj;
                        }

If we take phone number, pin code, county code as a private member in ContactDetails class, most of the time it would be empty. So how to design the class in such a way like extra details we could put it in another class and if needed for any entity we could use them.

Aucun commentaire:

Enregistrer un commentaire