Consider the next c++ code fragment
1. In an EXE:
Base.hpp
#ifndef _BASE_H_
#define _BASE_H_
class Base
{
public:
Base(){};
virtual double Add(double &x, double &y) = 0;
};
#endif
main.cpp
#include <iostream>
#include "Base.hpp"
#include "DerivedFactory.hpp"
void main()
{
Base *theBase = DerivedFactory::Create();
double x = 4.9, y = 3.3,z;
z = theBase->Add(x, y);//Works when Add is pure virtual function, but how???
//Linker error when Add is not pure virtual
}
2. In an implicitly linked DLL
Derived.hpp
#ifndef _DERIVED_H_
#define _DERIVED_H_
#include "Base.hpp"
class Derived : public Base
{
public:
double Add(double &x, double &y);
};
#endif
DerivedFactory.hpp
#ifndef _DERIVEDFACTORY_H_
#define _DERIVEDFACTORY_H_
#include "Derived.hpp"
class DerivedFactory
{
public:
__declspec(dllexport) static Derived* Create();
};
#endif
Derived.cpp
#include "Derived.hpp"
double Derived::Add(double &x, double &y)
{
return x + y;
}
DerivedFactory.cpp
#include "DerivedFactory.hpp"
Derived* DerivedFactory::Create()
{
Derived* theDerived = new Derived;
return theDerived;
}
The main question is how does the exe "know" to address the correct implementation of Add from the dll when the only exported function from it is Create()?
Why do I get linker error when Add() is "just" virtual and not pure virtual?