Re: counfused.. about rule of 3...
On Jun 19, 9:51 pm, SpreadTooThin <bjobrie...@gmail.com> wrote:
I am developing a class. It's a pretty simple one.
The class has one data member which is a std::string. The
purpose of the class it simple to make sure that the string
that is used as a constructor has an even length.
The class is called a uid.
I'm a little confused.. should this just inherit from
std::string ie class uid:public std::string ?
Probably not. You don't want to support all of the interface of
std::string: appending a single character to your uid would
break the invariant, for example.
I'm not sure I'm handling the copy constructors properly.
There's nothing you have to do. If the only data member of your
class is an std::string, the compiler will handle the copy
constructor, assignment and the destructor correctly. You don't
need any of the three.
class uid
{
private:
std::string id;
public:
uid(std::string _id)
{
id = _id;
if (id.size() & 1) // is the length odd?
id.append(" "); // yes. Now the length should be even
}
uid& operator=(std::string& _id)
{
id = _id;
if (id.size() & 1) // is the length odd?
id.append(" ");
}
Note that this is NOT a copy assignment operator, so the
compiler will still provide the copy assignment operator you
need. (And of course, you forgot the return at the end.)
uid& operator=(uid& _id)
{
id = _id;
}
Which is exactly what the compiler provided copy assignment will
do. Almost: in the compiler provided version, the parameter
will be a cosnt reference (which it should be), and the compiler
won't forget the return.
~uid(void)
{
// Nothing to do really.
So why bother providing it?
}
};
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34