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:
class Pet
{
public:
enum PetType { Dog, Cat, Bird, Fish };
void ToString()
{
switch(type)
{
case Pet::Dog: std::cout << "Dog" << std::endl; break;
case Pet::Cat: std::cout << "Cat" << std::endl; break;
case Pet::Bird: std::cout << "Bird" << std::endl; break;
case Pet::Fish: std::cout << "Fish" << std::endl; break;
}
}
private:
PetType type; // A type field.
};
class Dog : public Pet
{
public:
Dog() { type = Dog; }
};
// And so on...
void Test(const Pet& p) { p.ToString(); }
int main()
{
Dog d;
Test(d);
return 0;
}
This is an extraordinarily brittle way to implement a ToString()
method. Every time you need to add a derived class of Pet
, you would need to update the PetType
enumeration and the ToString()
method. For example, if I need a Turtle
subclass, I would need to make these changes:
// ...
enum PetType { Dog, Cat, Bird, Fish, Tutle /* Added */};
void ToString(const Pet& p)
{
switch(p.type)
{
case Pet::Dog: std::cout << "Dog" << std::endl; break;
case Pet::Cat: std::cout << "Cat" << std::endl; break;
case Pet::Bird: std::cout << "Bird" << std::endl; break;
case Pet::Fish: std::cout << "Fish" << std::endl; break;
case Pet::Turtle: std::cout << "Turtle" << std::endl; break; // Added
}
}
// ...
class Turtle : public Pet
{
public:
Turtle() { type = Turtle; } // Added
};
Imagine if the Pet
class had more functions than just ToString()
; maintenence becomes a nightmare. It's lot of code one needs to change, but the important thing is that in order to have a Turtle
class, I need to modify the Pet
class. 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 virtual
functions:
class Pet
{
public:
virtual void ToString() = 0;
};
class Dog : public Pet
{
public:
virtual void ToString() { std::cout << "Dog" << std::endl; }
};
class Turtle : public Pet
{
public:
virtual void ToString() { std::cout << "Turtle" << std::endl; }
};
// And so on...
void Test(const Pet& p) { p.ToString(); }
int main()
{
Turtle t
// Will call Turtle::ToString(), even though
// Test() was only given a const Pet&
Test(t);
return 0;
}
Note that the above code requires no extra enum
s or switch
statements. Calling Pet::ToString()
will call the correct implementation of ToString()
for Dog
s, Cat
s, etc. automatically, with much less code. I don't even need to change the Pet
class; I can just drop in a Turtle
class if needed, provided that Pet
has been defined.
For a possibly legitimate use of type fields, see this Stack Overflow question and the answers to that question.