Dynamic Constructors in C++???
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Dynamic Constructors in C++???

  1. #1
    Join Date
    Oct 2003
    Location
    Pune,India
    Posts
    107

    Dynamic Constructors in C++???

    Can anyone explain me what are Dynamic Constructors in C++?
    If possible give some example or provide with some reference article/link

    Thanks in advance

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,471

    Re: Dynamic Constructors in C++???

    I've not heard the term Dynamic Constructor used, but I'll take a guess that it's equivalent to the so-called "virtual constructor" or "clone method".

    Basically, it's a way of constructing an object based on the run-time type of some existing object. It basically uses standard virtual functions/polymorphism.
    Code:
    class base
    {
    public:
        virtual base* create() = 0;
        virtual base* clone() = 0;
    
    protected:
        base();
        base(const base&);
    };
    
    virtual der1 : public base
    {
    public:
        base* create() { return new der1; }
        base* clone() { return new der1(*this); }
        // etc...
    };
    
    virtual der2 : public base
    {
    public:
        base* create() { return new der2; }
        base* clone() { return new der2(*this); }
        // etc...
    };
    
    int main()
    {
        base* b = new der1;
    
        base* b1 = b->create();
        base* b2 = b->clone();
    }
    In the above, if I change the initialisation of b so that it points to a der2, then b1 and b2 will also point to a der2 object (a brand new one in the case of b1, and a copy of *b in the case of b2).
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  3. #3
    Join Date
    Oct 2003
    Location
    Pune,India
    Posts
    107

    Re: Dynamic Constructors in C++???

    Hi Graham,
    Thanks for the reply.
    Even I hadn't heard about this so called "Dynamic Constructors"
    But I was asked this question in an Interview. (Or did they actually meant Dynamic construction and it was mispelled as Constructor )
    Thanks a lot

    Regards,
    Sohail

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center