Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. why no virtual constructor?

why no virtual constructor?

Scheduled Pinned Locked Moved C / C++ / MFC
c++question
19 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S shanmugarajaa

    Dear friends, Why there is no virtual constructor in C++? Can anybody explain me.... Thanks and Regard, S.Shanmugaraja

    C Offline
    C Offline
    Chris Losinger
    wrote on last edited by
    #4

    what would/could such a thing accomplish?

    image processing toolkits | batch image processing

    1 Reply Last reply
    0
    • S shanmugarajaa

      Dear friends, Why there is no virtual constructor in C++? Can anybody explain me.... Thanks and Regard, S.Shanmugaraja

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #5

      See here.

      "One man's wage rise is another man's price increase." - Harold Wilson

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

      J 1 Reply Last reply
      0
      • D David Crow

        See here.

        "One man's wage rise is another man's price increase." - Harold Wilson

        "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

        "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

        J Offline
        J Offline
        jschell
        wrote on last edited by
        #6

        DavidCrow wrote:

        See here.

        I don't think I believe that. It says "In particular, "virtual" allows us to call a function knowing only an interfaces and not the exact type" And that seems to suffer from the same problem of equating a constructor to a method. With a virtual method I can do the following MyBase* p = ... p->myVirtualMethod() But it isn't possible to semantically create statements that are similar to that using a constructor. So the type would still be known.

        1 Reply Last reply
        0
        • S shanmugarajaa

          Dear friends, Why there is no virtual constructor in C++? Can anybody explain me.... Thanks and Regard, S.Shanmugaraja

          M Offline
          M Offline
          Mattias Hogstrom
          wrote on last edited by
          #7

          Consider the opposite, that it was possible. Subclassing, can sometimes be viewed as specialization. Dog is a specializations of an Animal. If the Animal has private variables, these are initialized in the constructor. If the constructor is virtual, it is replaced by a subclass' constructor. According to the principles of data hiding (public, protected, private), a sub class cannot access private member variables of a parent type. So these member variables would be left uninitialized. You don't want that because the parent class would break. If you by some reason need a virtual constructor there is a Design Pattern called the Template Method, http://en.wikipedia.org/wiki/Template\_method\_pattern In the example they have they define an algorithm in the parent class, and let the subclass define the implementation. It is of course possible to apply the same principle in constructors by creating a virtual method called "Initialize" which you call from the constructor. When this method is redefined in a subclass it will override the parent's definition. But I have never came across the need for a virtual constructor. Why do you need one?

          S J 2 Replies Last reply
          0
          • S sanjaylk
            1. In C++ Virtual functions are resolved by V_PTR (virtual pointer) at run time. 2) V_PTR points to its V_TABLE. 3) When an object is created, V_PTR is initialized in constructor. so if someone tries to define constructor as virtual, where and when V_PTR will be initialized?
            S Offline
            S Offline
            Stefan_Lang
            wrote on last edited by
            #8

            Correct for C++, but I prefer the response of jschell as this is in fact an OO-conundrum rather than being specific to C++.

            1 Reply Last reply
            0
            • J jschell

              The fact that a constructor looks like a method doesn't make it one. A Object in terms of Object Oriented Programming can have polymorphic behavior. But an Object does not exist until it has been successfully created. Thus it follows there can be no polymorphic behavior until after creation (constructor) succeeds. None of the common OO languages allow it. Additionally as per the other response on the technical issues there is also the concept that a parent class should be 'created' before a child. And with normal virtual semantics that would not be possible. With the current semantics it is.

              S Offline
              S Offline
              Stefan_Lang
              wrote on last edited by
              #9

              jschell wrote:

              But an Object does not exist until it has been successfully created. Thus it follows there can be no polymorphic behavior until after creation (constructor) succeeds.

              ^ this! You nailed it.

              1 Reply Last reply
              0
              • M Mattias Hogstrom

                Consider the opposite, that it was possible. Subclassing, can sometimes be viewed as specialization. Dog is a specializations of an Animal. If the Animal has private variables, these are initialized in the constructor. If the constructor is virtual, it is replaced by a subclass' constructor. According to the principles of data hiding (public, protected, private), a sub class cannot access private member variables of a parent type. So these member variables would be left uninitialized. You don't want that because the parent class would break. If you by some reason need a virtual constructor there is a Design Pattern called the Template Method, http://en.wikipedia.org/wiki/Template\_method\_pattern In the example they have they define an algorithm in the parent class, and let the subclass define the implementation. It is of course possible to apply the same principle in constructors by creating a virtual method called "Initialize" which you call from the constructor. When this method is redefined in a subclass it will override the parent's definition. But I have never came across the need for a virtual constructor. Why do you need one?

                S Offline
                S Offline
                Stefan_Lang
                wrote on last edited by
                #10

                You started on a good idea, i. e. posing the question 'what if?'. You raised the wrong question though, since initialization is not really a problem: C++ implicitly calls the constructors of its parent classes! Instead you should have asked this: What if ... 1. I had a class called Animal 2. two subclasses called cat and mouse 3. a virtual constructor for Animal. --> what would that constructor create? There is no answer to this question: in order to decide what subclass to create, you'd need to decide what type the object is of. But to decide the type, you'd need to create the object first! It is a typical hen-and-egg problem. It cannot be solved. Therefore there is no sense in a virtual constructor. There is a mechanism for methods that do not require an actual instance of an object: static. But you cannot override a static method, exactly because it is not tied to an instance, and therefore there is no way to resolve a virtual call!

                M A 2 Replies Last reply
                0
                • S shanmugarajaa

                  Dear friends, Why there is no virtual constructor in C++? Can anybody explain me.... Thanks and Regard, S.Shanmugaraja

                  E Offline
                  E Offline
                  Eugen Podsypalnikov
                  wrote on last edited by
                  #11

                  // Why there is no virtual constructor in C++? Can anybody explain me.... It would be a construction of a tool without its material :) : - shaping of the hammer's hold, but without wood - sharpening of the knife, but without steel - ...

                  They sought it with thimbles, they sought it with care; They pursued it with forks and hope; They threatened its life with a railway-share; They charmed it with smiles and soap. :)

                  1 Reply Last reply
                  0
                  • S Stefan_Lang

                    You started on a good idea, i. e. posing the question 'what if?'. You raised the wrong question though, since initialization is not really a problem: C++ implicitly calls the constructors of its parent classes! Instead you should have asked this: What if ... 1. I had a class called Animal 2. two subclasses called cat and mouse 3. a virtual constructor for Animal. --> what would that constructor create? There is no answer to this question: in order to decide what subclass to create, you'd need to decide what type the object is of. But to decide the type, you'd need to create the object first! It is a typical hen-and-egg problem. It cannot be solved. Therefore there is no sense in a virtual constructor. There is a mechanism for methods that do not require an actual instance of an object: static. But you cannot override a static method, exactly because it is not tied to an instance, and therefore there is no way to resolve a virtual call!

                    M Offline
                    M Offline
                    Mattias Hogstrom
                    wrote on last edited by
                    #12

                    Yes the default behavior is that all constructors execute, the subclass and all its parents constructors, so initialization isn't a problem. Overriding is generally done by declaring methods virtual. I thought he meant how to "override" the constructor, but that doesn't make much sense. That was my point I was trying to get to. You were asking on the other hand asking: What would a virtual constructor create? But what is actually common is to have virtual methods that create subclass objects. This is how the factory pattern works. The parent class provides a CreateInstance Method. specialized factory implementations(subclasses), create related objects of the same family. An SqlServerConnection object provides a CreateCommand method that returns a SqlServerCommand, whereas the OracleConnection object's CreateCommand would return an OracleCommand. The Create methods are not class constructors, but they are constructing objects. It is probably not safe to call virtual methods from a constructor, because the parent constructors execute before the constructors of the subclasses have finished.

                    S 1 Reply Last reply
                    0
                    • M Mattias Hogstrom

                      Yes the default behavior is that all constructors execute, the subclass and all its parents constructors, so initialization isn't a problem. Overriding is generally done by declaring methods virtual. I thought he meant how to "override" the constructor, but that doesn't make much sense. That was my point I was trying to get to. You were asking on the other hand asking: What would a virtual constructor create? But what is actually common is to have virtual methods that create subclass objects. This is how the factory pattern works. The parent class provides a CreateInstance Method. specialized factory implementations(subclasses), create related objects of the same family. An SqlServerConnection object provides a CreateCommand method that returns a SqlServerCommand, whereas the OracleConnection object's CreateCommand would return an OracleCommand. The Create methods are not class constructors, but they are constructing objects. It is probably not safe to call virtual methods from a constructor, because the parent constructors execute before the constructors of the subclasses have finished.

                      S Offline
                      S Offline
                      Stefan_Lang
                      wrote on last edited by
                      #13

                      Mattias Högström wrote:

                      You were asking on the other hand asking:
                      What would a virtual constructor create? But what is actually common is to have virtual methods that create subclass objects.

                      That is not a valid answer to my question. There is in fact no valid answer. And that is the point of the question! Of course using factories or similar is a reasonable solution in such a situation - but that was not my question, nor the OPs'.

                      M 1 Reply Last reply
                      0
                      • S Stefan_Lang

                        Mattias Högström wrote:

                        You were asking on the other hand asking:
                        What would a virtual constructor create? But what is actually common is to have virtual methods that create subclass objects.

                        That is not a valid answer to my question. There is in fact no valid answer. And that is the point of the question! Of course using factories or similar is a reasonable solution in such a situation - but that was not my question, nor the OPs'.

                        M Offline
                        M Offline
                        Mattias Hogstrom
                        wrote on last edited by
                        #14

                        I didn't try to answer your question :) The original question was "why no virtual constructor" (I suppose he is asking because there are virtual destructors) You are confusing me.... talking about valid answers. There is probably a reason why there is no virtual constructor in C++ If the language designer would have wanted one, it could have been added regardless if it was useful or not.

                        1 Reply Last reply
                        0
                        • S Stefan_Lang

                          You started on a good idea, i. e. posing the question 'what if?'. You raised the wrong question though, since initialization is not really a problem: C++ implicitly calls the constructors of its parent classes! Instead you should have asked this: What if ... 1. I had a class called Animal 2. two subclasses called cat and mouse 3. a virtual constructor for Animal. --> what would that constructor create? There is no answer to this question: in order to decide what subclass to create, you'd need to decide what type the object is of. But to decide the type, you'd need to create the object first! It is a typical hen-and-egg problem. It cannot be solved. Therefore there is no sense in a virtual constructor. There is a mechanism for methods that do not require an actual instance of an object: static. But you cannot override a static method, exactly because it is not tied to an instance, and therefore there is no way to resolve a virtual call!

                          A Offline
                          A Offline
                          Albert Holguin
                          wrote on last edited by
                          #15

                          What came first, the chicken or the pure virtual CAnimal?

                          1 Reply Last reply
                          0
                          • M Mattias Hogstrom

                            Consider the opposite, that it was possible. Subclassing, can sometimes be viewed as specialization. Dog is a specializations of an Animal. If the Animal has private variables, these are initialized in the constructor. If the constructor is virtual, it is replaced by a subclass' constructor. According to the principles of data hiding (public, protected, private), a sub class cannot access private member variables of a parent type. So these member variables would be left uninitialized. You don't want that because the parent class would break. If you by some reason need a virtual constructor there is a Design Pattern called the Template Method, http://en.wikipedia.org/wiki/Template\_method\_pattern In the example they have they define an algorithm in the parent class, and let the subclass define the implementation. It is of course possible to apply the same principle in constructors by creating a virtual method called "Initialize" which you call from the constructor. When this method is redefined in a subclass it will override the parent's definition. But I have never came across the need for a virtual constructor. Why do you need one?

                            J Offline
                            J Offline
                            jschell
                            wrote on last edited by
                            #16

                            Mattias Högström wrote:

                            It is of course possible to apply the same principle in constructors by creating a virtual method called "Initialize" which you call from the constructor. When this method is redefined in a subclass it will override the parent's definition.

                            I don't think so. http://www2.research.att.com/~bs/bs_faq2.html#vcall[^] And even if it is now possible (or possible in other OO languages) it is something that should be used with a great deal of care. The reason for that is that because it is virtual then intent would be that it interacts both with the parent and child. And not understanding exactly how the parent and child are designed to work and not understanding in detail how the child parent are implemented can lead to problems. Especially when one considers maintenance. And often when people want to do this it is because they do not understand the above or even understand what constructors are. So probably best to just say - don't do it.

                            M 1 Reply Last reply
                            0
                            • J jschell

                              Mattias Högström wrote:

                              It is of course possible to apply the same principle in constructors by creating a virtual method called "Initialize" which you call from the constructor. When this method is redefined in a subclass it will override the parent's definition.

                              I don't think so. http://www2.research.att.com/~bs/bs_faq2.html#vcall[^] And even if it is now possible (or possible in other OO languages) it is something that should be used with a great deal of care. The reason for that is that because it is virtual then intent would be that it interacts both with the parent and child. And not understanding exactly how the parent and child are designed to work and not understanding in detail how the child parent are implemented can lead to problems. Especially when one considers maintenance. And often when people want to do this it is because they do not understand the above or even understand what constructors are. So probably best to just say - don't do it.

                              M Offline
                              M Offline
                              Mattias Hogstrom
                              wrote on last edited by
                              #17

                              you're right. I remember reading that before. It is unsafe or undefined to call a virtual method from the constructor. I was mearly trying to show the usage of virtual methods that can create objects by delegating the exact type to a subclass to define it. This is how some factories are implemented. But I should have stopped there. I went too far. Calling them from constructors are of course not possible due to how parents an children are created. I have never found any need for a virtual constructor, but virtual methods that create objects often.

                              J 1 Reply Last reply
                              0
                              • M Mattias Hogstrom

                                you're right. I remember reading that before. It is unsafe or undefined to call a virtual method from the constructor. I was mearly trying to show the usage of virtual methods that can create objects by delegating the exact type to a subclass to define it. This is how some factories are implemented. But I should have stopped there. I went too far. Calling them from constructors are of course not possible due to how parents an children are created. I have never found any need for a virtual constructor, but virtual methods that create objects often.

                                J Offline
                                J Offline
                                jschell
                                wrote on last edited by
                                #18

                                Mattias Högström wrote:

                                It is unsafe or undefined to call a virtual method from the constructor.

                                It is defined behavior.

                                Mattias Högström wrote:

                                Calling them from constructors are of course not possible due to how parents an children are created

                                Not sure what that means. It not possible because the language definition doesn't allow it. Perhaps your reason is a restatement of why that rule exists.

                                M 1 Reply Last reply
                                0
                                • J jschell

                                  Mattias Högström wrote:

                                  It is unsafe or undefined to call a virtual method from the constructor.

                                  It is defined behavior.

                                  Mattias Högström wrote:

                                  Calling them from constructors are of course not possible due to how parents an children are created

                                  Not sure what that means. It not possible because the language definition doesn't allow it. Perhaps your reason is a restatement of why that rule exists.

                                  M Offline
                                  M Offline
                                  Mattias Hogstrom
                                  wrote on last edited by
                                  #19

                                  jschell wrote:

                                  It is defined behavior.

                                  I suppose you mean that the defined behavior is that it isn´t allowed. I meant that its behavior would be undefined if it was allowed.

                                  jschell wrote:

                                  Not sure what that means. It not possible because the language definition doesn't allow it. Perhaps your reason is a restatement of why that rule exists.

                                  Yes.

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups