hi all
I am new to the C++ please help me what is the use of virtual constructors in c++, and when we can use these virtual constructors.
VIrtual constructor is a concept which doesnot exist in C++ but that provides you to implement one.
First thing first
Why do we require a virtual construct?
When you just consider virtual functions, it is concept which is completely based on type of object (not the type of pointer/reference to that object). ie the functions are called at runtime not compile time.
Now conside this example
Base* b = new Derived();
Hope I'm clear and not mistaken. If I'm wrong please comment.
Unlike ordinary member function, a constructor allows you to construct the type of the object at compile time. In above case, the complete object is created at compile time , this does not delay till runtime. So, the concept of virtual constructor is vague in this concept.
But you can provide the concept using virtual functions
Conside this example
- class Browser
-
{
-
public:
-
Browser(){}
-
Browser(const Browser&){}
-
virtual Browser* construct()
-
{
-
return new Browser();
-
}
-
-
virtual Browser* clone()
-
{
-
return new Browser(*this);
-
}
-
virtual ~Browser(){}
-
};
-
-
class HTML : public Browser
-
{
-
public:
-
HTML(){}
-
HTML(const HTML&){}
-
HTML* construct()
-
{
-
return new HTML();
-
}
-
-
HTML* clone()
-
{
-
return new Browser(*this);
-
}
-
virtual ~HTML(){}
-
};
-
-
void userCode( Browser& b)
-
{
-
Browser* bw = b.construct();
-
//use bw
-
delete bw;
-
}
This allows you to instatiate a new object of the right type without having to know the type of source object.