what is the use of virtual constructors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • suneel
    New Member
    • Oct 2006
    • 1

    what is the use of virtual constructors

    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.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I have never seen, nor do I believe that it is correct syntax to have, a virtual constructor.

    Comment

    • vermarajeev
      New Member
      • Aug 2006
      • 180

      #3
      Originally posted by suneel
      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

      Code:
      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.

      Comment

      Working...