CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2008
    Posts
    48

    Why we don't have Virtual Constructor when we have Virtual Destructor ?

    Hi,
    Is there any technical reason behind for not having a Virtual Constructor ?

    Upto my knowledge it may be because, since we know the type of constructor we are calling(which implicitly says that, we know the type of object) there is no need to have Virtual keyword for constructors ?

    Is my analysis correct ?

    Thanks

  2. #2
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?

    Late binding is based on the principle that the correct function is called based on the class of the object. So calling a virtual function via a base class pointer/reference will call the correct function based on the objects real class. Likewise, destroying an object via a base class pointer will correctly call the destructor of the objects real class.

    When creating a new object the object does not exist yet, so no decision can be made based on its real class.
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?

    Not only is there no need, but it doesn't make logical sense. To create an object you have to specify its type. If there were such a thing as a virtual constructor, how would you invoke it?

  4. #4
    Join Date
    Nov 2003
    Posts
    1,405

    Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?

    Quote Originally Posted by rsodimbakam
    there is no need to have Virtual keyword for constructors ?
    Constructors cannot be virtual (for the reason you indicate) but you can easily introduce a virtual construction function (which can overridden in derived classes). This gives you the effect of a virtual constructor.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured