Re: linker error in virtual function
On Apr 14, 10:06 am, Michael DOUBEZ <michael.dou...@free.fr> wrote:
Rahul a =E9crit :
I have the following polymorphic classes,
class Shape
{
public : virtual void draw()
{
}
virtual void sample();
};
class Circle : public Shape
{
public : virtual void draw()
{
cout<<"Circle::draw"<<endl;
}
};
int main()
{
Shape *ptr = new Circle;
ptr->draw();
return(0);
}
and i get a linker error saying undefined external sumbol __sample...
But i haven't really invoked the function sample(). Note that the code
works fine when i change sample() to a non-virtual function prototype,
why is this the case?
If you make it virtual, 10.3-8 of the standard requires that:
"A virtual function declared in a class shall be defined or
declared pure or both; but no diagnostic is required."
That's just a note; the normative text is in =A73.2: "A virtual
function is used if it is not pure." If a function is used,
then there must be a definition (and only one, unless it is a
template or inline). Otherwise, undefined behavior occurs.
I wonder, however, if this shouldn't read: "a virtual function
is used if it is not pure, and the class is instantiated"? (I
can imagine scenarios where you pull in some header which
defines a class with virtual functions, but you don't actually
use the class, nor link against the library which contains the
definitions. As it now reads, this is undefined behavior.)
Here you don't have the diagnostic of missing definition but
the linker requires it (for its virtual table).
That's still a diagnostic. Not required, but in practice, I
think you'll almost always get 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