I have learned that
type fields is an error-prone technique somewhere
I have Google it much but no satisfactory results .Although I know the meaning of type and fields individually . I am thinking that type field means field of a particular type like
class marks;
class test {
marks number;
bool pass;
}
Here according to me type field is number and pass .
If this is right how is composition different from it?
Also what is type field technique?? How it is error prone??
Please give it true meaning. Also give an example to show its evil nature and what are its substitutes ??
You’re almost certainly referring to type fields as discussed in the book The C++ Programming Language by Bjarne Stroustrup. A type field in this context would simply be a variable of some kind in a base class that indicates the actual type of its subclasses. Here’s an example:
This is an extraordinarily brittle way to implement a
ToString()method. Every time you need to add a derived class ofPet, you would need to update thePetTypeenumeration and theToString()method. For example, if I need aTurtlesubclass, I would need to make these changes:Imagine if the
Petclass had more functions than justToString(); maintenence becomes a nightmare. It’s lot of code one needs to change, but the important thing is that in order to have aTurtleclass, I need to modify thePetclass. That means more testing, code review, etc. is needed. It’s a clear violation of the open/closed principle. That’s why type fields are extremely error-prone.A significantly superior way would be to use
virtualfunctions:Note that the above code requires no extra
enums orswitchstatements. CallingPet::ToString()will call the correct implementation ofToString()forDogs,Cats, etc. automatically, with much less code. I don’t even need to change thePetclass; I can just drop in aTurtleclass if needed, provided thatPethas been defined.For a possibly legitimate use of type fields, see this Stack Overflow question and the answers to that question.