|
-
November 3rd, 2010, 08:56 AM
#1
[Discussion] Modifying a class' behaviour - inheritance pitfalls
Let's say we had the following class. As it stands, once constructed there is no way to change the contents of the string.
Code:
class String
{
String(const char* text);
{
data = (char*)malloc(strlen(text)+1);
strcpy(data, text);
}
virtual size_t length() const
{
return strlen(data);
}
const char* c_str() const
{
return data;
}
// destructor, copy and assignment implemented.
// ...
private:
char* data;
};
Now someone might extend that class to report the length faster. We know the length never changes so we only need to measure it once:
Code:
class FastString : public String
{
public:
FastString(const char* text) : String(text)
{
len = strlen( c_str() );
}
virtual size_t length() const
{
return len;
}
// destructor, copy and assignment implemented.
// ...
private:
size_t len;
};
However, if the original class 'String' is then changed such that its contents can be changed, the derived class will stop working. Note that this would happen despite the implementation of the original class being completely private.
An alternative would be that the original class is never changed, but that the new behaviour is also implemented in a separate derived class. Downside being that the original class would have to expose some of its implementation to derived classes, maybe by making data protected rather than private. That in itself opens up even more problems because then even the implementation cannot be changed without breaking derived classes.
The only solution I see is documenting what is guaranteed about a class and other authors not making assumptions about how the base class will behave in future.
The documentation might say that String will always remain immutable, in which case FastString should always work, but if no such guarantee is given then the author of FastString should be very careful about the assumptions he makes.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|