Understanding "g undefined reference to typeinfo" Errors
When encountering "undefined reference to typeinfo" linker errors, it's crucial to delve into the underlying reasons behind these messages. One potential cause lies in declaring virtual functions without providing their definitions.
Virtual functions allow for polymorphism, enabling derived classes to override and provide different implementations for methods inherited from their base classes. However, when a virtual function is declared without a definition, the compiler indicates that the implementation is provided elsewhere. This means the linker will attempt to find the missing definition during the linking stage, referencing other compilation units or libraries.
To eliminate this error, the virtual function must be accompanied by a definition. This associates the function declaration with its implementation, preventing the linker from attempting to resolve the reference later. A defined virtual function appears as:
virtual void fn() { /* insert code here */ }
In contrast, a virtual function declaration without a definition resembles:
virtual void fn();
This declaration fails to provide the definition, resulting in the "undefined reference to typeinfo" error.
Analogously, it's comparable to declaring an external variable without defining it:
extern int i; int *pi = &i;
In this instance, the compiler indicates that the 'i' integer is declared elsewhere and must be resolved during linking. Otherwise, pi cannot refer to its address.
The above is the detailed content of Why Does My C Code Produce 'undefined reference to typeinfo' Errors?. For more information, please follow other related articles on the PHP Chinese website!