View Single Post
Old May 26th, 2006, 5:59 PM   #10
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,253
Rep Power: 5 grumpy will become famous soon enough
Quote:
Originally Posted by Laterix
I actually call pure virtual function from abstract class constructor. And I think that is really a problem, because when I create a new object of SpesificAdapter it automatically calls parent class constructor before it own and there it trys to call operation2() which doesn't exists yet. Am I rigt?
Yes, you're right. It is generally bad practice to call any virtual function from a constructor (whether pure or not). The reason is that the constructor can only call a virtual function statically (i.e. the constructor for Base can only call Base::virtual_function(), which is not normally the intent of calling a virtual function). The reason for this is construction order: a Base class constructor is invoked before the derived class constructor and various properties of the class do not come together until the derived class is constructed. This means that, when the Base constructor is called, there is no information available to say the object is really a Derived, which mean that Derived::virtual_function() cannot be invoked.

Pure virtual functions are worse: being pure virtual, they might not be defined by the base class, which means there is no Base::virtual_function() to call. That normally shows up as a linker error.
Quote:
Originally Posted by Laterix
Anyway, I found a workaround to this problem. You have been very nice. Hopefully I can help someone with Java or PHP in the future.
The workaround is to create the object, before calling the virtual function. For example (using your case);
Base *object = new Derived;
object->virtual_function();
object->nonvirtual_which_calls_virtual_function();
grumpy is offline   Reply With Quote