A friend and I had a very interesting discussion about the construction of Objects that ended up with this piece of code:
#include <iostream> class Parent { public: Parent( ) { this->doSomething( ); } virtual void doSomething( ) = 0; }; class Child : public Parent { int param; public: Child( ) { param = 1000; } virtual void doSomething( ) { std::cout << "doSomething( " << param << " )" << std::endl; } }; int main( void ) { Child c; return 0; } I know that the standard does not define the behavior when a pure virtual function is called from a constructor or destructor, also this is not a practical example of how i would write code in production, it is just a test to check what the compiler does.
Testing the same construct in Java prints
doSomething( 0 )
That makes sense since param is not initialized at the point doSomething() is called from the parent constructor.
I would expect similar behavior in C++, with the difference that param contains anything at the time the function is called.
Instead compiling the above code results in a linker error with (c++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3) saying that the reference to Parent::doSomething( ) is undefined.
So, my question is: Why is this a linker error? If this is an error, I would expect the compiler to complain, especially because there is an implementation of the function. Any insight of how the linker works in this case or a reference to further reading would be highly appreciated.
Thank you in advance! I hope that this question is not a duplicate, but i could not find a similar question..