alternativa said:
Hi,
what would you say - which way of building a class is better? Why?
/**** 1 ****/
class Person {
public:
Person(char *n, char *sn, int d);
~Person();
protected:
char *name;
char *second_name;
int date_of_birth;
};
/**** 2 ****/
class Person {
char name;
char second_name;
int date_of_birth;
public:
Person(char n, char sn, int d);
~Person();
};
class Person
{
private:
std::string m_name;
std::string m_second_name;
int m_date_of_birth;
public:
Person(std::string const &i_name, std::string const &i_second_name, int
i_date_of_birth) :
m_name(i_name), m_second_name(i_second_name),
m_date_of_birth(i_date_of_birth) {}
std::string const &name() const {return m_name;}
std::string const &second_name() const {return m_second_name;}
int date_of_birth() const {return date_of_birth;}
// no destructor
};
std::string should be preferred over char * in modern C++ programming,
mostly because it just makes things so much easier and less error prone.
It is usually better to initialize a std::string with another std::string.
If you have a char * it still works fine:
Person p("Elmer", "Fudd", 19898973);
and if you already have std::strings you can just write
Person q(astring, bstring, date);
rather than the awkward
Person q(astring.c_str(), bstring.c_str(), date);
If you need a destructor (which you don't when using std::string) you
probably also need a copy constructor and assignment operator. Google for
"C++ rule of 3".
Some programmers reflexively write get/set pairs for each data item. I think
that's a bad habit. You can use the constructor itself to change the data
values:
p = Person("Daffy", "Duck", 890);
This usage emphasizes the idea that a Person is an object rather than just
three related values.
Cy