How to construct virtual constructor

Answer Posted / mmszubeir

C++ doesn’t give any direct support to declare a virtual
constructor as such. But we can have a virtual constructor
by indirectly providing the mechanism.

As like ordinary virtual functions, a virtual constructor
can exhibit different behaviors depending upon the request.
That is, a virtual constructor can construct different
types of objects on different requests. This implies the
class hierarchy should be polymorphical.

This technique resembles two stage construction technique.
To avoid breaking at the constructor of an object, we keep
the heavy initialization code in a separate initializer
function so that we get the minimum guarantee that the
constructor won’t fail.
In this case, we first invoke the constructor and then
invoke the initializer function. The advantage of this
method is that we will have a better control of the
construction.

For example,

CBrush blueBrush; // Just an object. Must be initialized!
blueBrush.CreateSolidBrush(RGB(0,0,255)); // Blue brush.

Since I am running short of time, I hang on with this for
the time being. I will add more details about the virtual
constructor theory soon.

Is This Answer Correct ?    10 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

If you don’t declare a return value, what type of return value is assumed?

721


What is stoi in c++?

897


What is the difference between an external iterator and an internal iterator? Describe an advantage of the external iterator.

771


What is enum class in c++?

914


Is std :: string immutable?

750


How new/delete differs from malloc()/free?

819


What is setbase c++?

811


What's the order in which the objects in an array are destructed?

1126


Tell me difference between constant pointer and pointer to a constant.

839


What is the difference between c++ and turbo c++?

773


What is the sequence of destruction of local objects?

708


Evaluate as true or false: !(1 &&0 || !1) a) True b) False c) Invalid statement

825


What should main() return in c and c++?

731


What is function prototyping?

817


What is the difference between equal to (==) and assignment operator (=)?

765