Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. is it possible to override destructor ? what care we have to take when we use it ?
QtWS25 Last Chance

is it possible to override destructor ? what care we have to take when we use it ?

Scheduled Pinned Locked Moved Solved C++ Gurus
26 Posts 8 Posters 9.7k Views
  • 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.
  • Q Offline
    Q Offline
    Qt embedded developer
    wrote on 6 Jul 2022, 13:32 last edited by
    #1

    I have seen that we can not override the constructor. but i want to know is it possible to override the destructor. what we have to take care when we override destructor ?

    J 1 Reply Last reply 6 Jul 2022, 13:38
    0
    • J JonB
      6 Jul 2022, 16:26

      @Chris-Kawa
      I clearly need to read up on this! I am not understanding when you are saying I should vs should not go for a virtual ~ :)

      • What do I need to read (preferably simple!)?

      • I may be mistaken, but I believe if you let Creator generate your widget class it puts in an empty virtual destructor automatically? Why that? [Oh, maybe it's not empty, it will have that delete ui statement. OK, but they mark it virtual, right?]

      C Offline
      C Offline
      Chris Kawa
      Lifetime Qt Champion
      wrote on 6 Jul 2022, 16:43 last edited by Chris Kawa 7 Jun 2022, 16:51
      #11

      @JonB said:

      What do I need to read (preferably simple!)?

      For the gist of it this example is enough:

      class Base() {};
      
      class Derived: public Base
      {
      public:
          ~Derived() { /* delete something */ }
      };
      
      int main()
      {
         Base* foo = new Derived();
         delete foo; // Oh no! ~Derived is not called and something leaks. Should've used virtual!
      }
      

      if you let Creator generate your widget class (...)

      Widgets are derived from QObject, which is a polymorphic class with virtual destructor, so any derived class has a virtual destructor whether you specify it or not. Creator puts it there just to be explicit, for readability sake.

      As to when you should make destructor virtual? When you expect your class to be derived from and have polymorphic behavior. To explain it with examples: QObject is expected to be derived from and derived classes often deallocate resources in their destructors, so polymorphic destruction behavior is indeed very much desired here, and lack of it would lead to leaks and broken behavior.
      On the other hand a value-class like QPoint has no business being derived from and there's no excuse to pay for virtual destructor call in its case, so it doesn't have a virtual destructor. Sure, you can shoot yourself in the foot derive from it and deallocate some dynamic resources in the derived destructor, but honestly that's on you for using it that way. There's even a protection for that in the language - you can make your class final and make sure nobody abuses it this way.

      Consider this:

      class Point2D
      {
      public:
         int x = 0;
         int y = 0;
      };
      
      class Point3D : public Point2D
      {
      public: 
         int z = 0;
      }
      

      Even if you do

      Point2D* p = new Point3D();
      delete p;
      

      nothing is leaked. There's absolutely no need here for vtables cost associated with them.

      1 Reply Last reply
      6
      • Q Qt embedded developer
        6 Jul 2022, 13:32

        I have seen that we can not override the constructor. but i want to know is it possible to override the destructor. what we have to take care when we override destructor ?

        J Offline
        J Offline
        JonB
        wrote on 6 Jul 2022, 13:38 last edited by
        #2

        @Qt-embedded-developer
        You can override both constructors & destructors. In constructors your code runs after the base constructor, in destructors your code runs before the base destructor. For example, when you create a new Qt widget project from Creator the generated code will have overrides for both the constructor and destructor.

        Q 1 Reply Last reply 6 Jul 2022, 14:37
        2
        • J Offline
          J Offline
          JoeCFD
          wrote on 6 Jul 2022, 13:49 last edited by JoeCFD 7 Jun 2022, 13:50
          #3

          Traditionally in C++ it is better always to override destructors to avoid memory leak. In VS, virtual is added to all destructors automatically when new classes are created if I remember correctly.

          Q 1 Reply Last reply 6 Jul 2022, 14:38
          1
          • J JonB
            6 Jul 2022, 13:38

            @Qt-embedded-developer
            You can override both constructors & destructors. In constructors your code runs after the base constructor, in destructors your code runs before the base destructor. For example, when you create a new Qt widget project from Creator the generated code will have overrides for both the constructor and destructor.

            Q Offline
            Q Offline
            Qt embedded developer
            wrote on 6 Jul 2022, 14:37 last edited by
            #4

            @JonB I heard from many place that in c++ constructor overriding not possible.

            J K 2 Replies Last reply 6 Jul 2022, 14:55
            0
            • J JoeCFD
              6 Jul 2022, 13:49

              Traditionally in C++ it is better always to override destructors to avoid memory leak. In VS, virtual is added to all destructors automatically when new classes are created if I remember correctly.

              Q Offline
              Q Offline
              Qt embedded developer
              wrote on 6 Jul 2022, 14:38 last edited by
              #5

              @JoeCFD can you let me know what things we have to take care while override it.

              J 1 Reply Last reply 6 Jul 2022, 15:10
              0
              • Q Qt embedded developer
                6 Jul 2022, 14:37

                @JonB I heard from many place that in c++ constructor overriding not possible.

                J Offline
                J Offline
                JonB
                wrote on 6 Jul 2022, 14:55 last edited by JonB 7 Jun 2022, 15:08
                #6

                @Qt-embedded-developer said in is it possible to override destructor ? what care we have to take when we use it ?:

                @JonB I heard from many place that in c++ constructor overriding not possible.

                Since almost any class you have written which derives from another class has its own constructor I don't know what you mean. Maybe it's a question of semantics (wording) here? I did say it differs from overriding a virtual method in that you cannot choose not to call the base constructor, if that is what you are thinking of, and the compiler automatically calls that before it enters your constructor's body, But then that is similar for the destructor, it calls the base destructor after any override destructor code you might choose to add, so far as I know you cannot prevent that.

                If you "heard from many place" then post some link(s), maybe that will clarify what we are talking/you are asking about.

                I will let others better versed in C++ than I answer further. There is a difference, in that constructors cannot be marked virtual while destructors can & should be marked virtual. You can write override against a destructor but not against a constructor. And this is probably related to what you are saying. But so far as I can see constructors & destructors should be thought of in the same way, with the compiler generating extra code before/after any definition you give.

                I know that you should not/cannot call any virtual methods from a constructor, as the vtable has not been set up yet. From your own destructor I believe you can still call virtual methods. But it may be dodgy.

                1 Reply Last reply
                3
                • J Offline
                  J Offline
                  JoeCFD
                  wrote on 6 Jul 2022, 15:09 last edited by
                  #7

                  Are you talking about overloading? There is no such thing like override constructor.

                  1 Reply Last reply
                  0
                  • Q Qt embedded developer
                    6 Jul 2022, 14:38

                    @JoeCFD can you let me know what things we have to take care while override it.

                    J Offline
                    J Offline
                    JoeCFD
                    wrote on 6 Jul 2022, 15:10 last edited by JoeCFD 7 Jun 2022, 15:11
                    #8

                    @Qt-embedded-developer add virtual to all of your destructors and make it a habit.

                    C J 2 Replies Last reply 6 Jul 2022, 16:15
                    0
                    • J JoeCFD
                      6 Jul 2022, 15:10

                      @Qt-embedded-developer add virtual to all of your destructors and make it a habit.

                      C Offline
                      C Offline
                      Chris Kawa
                      Lifetime Qt Champion
                      wrote on 6 Jul 2022, 16:15 last edited by Chris Kawa 7 Jun 2022, 16:20
                      #9

                      @JoeCFD said:

                      In VS, virtual is added to all destructors automatically when new classes are created

                      No, it's not.

                      add virtual to all of your destructors and make it a habit.

                      That's a terrible advice! Why would you recommend that?
                      Destructors only need to be virtual when they have a need to be virtual. Virtual destructors ensure that objects are destroyed polymorphycally i.e. calling delete on base class pointer will call derived class' destructor first. That's it. This is not always needed and has a cost in the form of vtable call. You should only pay that cost when you need that functionality, not out of habit!

                      J 1 Reply Last reply 6 Jul 2022, 16:26
                      3
                      • C Chris Kawa
                        6 Jul 2022, 16:15

                        @JoeCFD said:

                        In VS, virtual is added to all destructors automatically when new classes are created

                        No, it's not.

                        add virtual to all of your destructors and make it a habit.

                        That's a terrible advice! Why would you recommend that?
                        Destructors only need to be virtual when they have a need to be virtual. Virtual destructors ensure that objects are destroyed polymorphycally i.e. calling delete on base class pointer will call derived class' destructor first. That's it. This is not always needed and has a cost in the form of vtable call. You should only pay that cost when you need that functionality, not out of habit!

                        J Offline
                        J Offline
                        JonB
                        wrote on 6 Jul 2022, 16:26 last edited by JonB 7 Jun 2022, 16:28
                        #10

                        @Chris-Kawa
                        I clearly need to read up on this! I am not understanding when you are saying I should vs should not go for a virtual ~ :)

                        • What do I need to read (preferably simple!)?

                        • I may be mistaken, but I believe if you let Creator generate your widget class it puts in an empty virtual destructor automatically? Why that? [Oh, maybe it's not empty, it will have that delete ui statement. OK, but they mark it virtual, right?]

                        C 1 Reply Last reply 6 Jul 2022, 16:43
                        1
                        • J JonB
                          6 Jul 2022, 16:26

                          @Chris-Kawa
                          I clearly need to read up on this! I am not understanding when you are saying I should vs should not go for a virtual ~ :)

                          • What do I need to read (preferably simple!)?

                          • I may be mistaken, but I believe if you let Creator generate your widget class it puts in an empty virtual destructor automatically? Why that? [Oh, maybe it's not empty, it will have that delete ui statement. OK, but they mark it virtual, right?]

                          C Offline
                          C Offline
                          Chris Kawa
                          Lifetime Qt Champion
                          wrote on 6 Jul 2022, 16:43 last edited by Chris Kawa 7 Jun 2022, 16:51
                          #11

                          @JonB said:

                          What do I need to read (preferably simple!)?

                          For the gist of it this example is enough:

                          class Base() {};
                          
                          class Derived: public Base
                          {
                          public:
                              ~Derived() { /* delete something */ }
                          };
                          
                          int main()
                          {
                             Base* foo = new Derived();
                             delete foo; // Oh no! ~Derived is not called and something leaks. Should've used virtual!
                          }
                          

                          if you let Creator generate your widget class (...)

                          Widgets are derived from QObject, which is a polymorphic class with virtual destructor, so any derived class has a virtual destructor whether you specify it or not. Creator puts it there just to be explicit, for readability sake.

                          As to when you should make destructor virtual? When you expect your class to be derived from and have polymorphic behavior. To explain it with examples: QObject is expected to be derived from and derived classes often deallocate resources in their destructors, so polymorphic destruction behavior is indeed very much desired here, and lack of it would lead to leaks and broken behavior.
                          On the other hand a value-class like QPoint has no business being derived from and there's no excuse to pay for virtual destructor call in its case, so it doesn't have a virtual destructor. Sure, you can shoot yourself in the foot derive from it and deallocate some dynamic resources in the derived destructor, but honestly that's on you for using it that way. There's even a protection for that in the language - you can make your class final and make sure nobody abuses it this way.

                          Consider this:

                          class Point2D
                          {
                          public:
                             int x = 0;
                             int y = 0;
                          };
                          
                          class Point3D : public Point2D
                          {
                          public: 
                             int z = 0;
                          }
                          

                          Even if you do

                          Point2D* p = new Point3D();
                          delete p;
                          

                          nothing is leaked. There's absolutely no need here for vtables cost associated with them.

                          1 Reply Last reply
                          6
                          • J Offline
                            J Offline
                            JoeCFD
                            wrote on 6 Jul 2022, 23:05 last edited by JoeCFD 7 Jun 2022, 23:19
                            #12

                            @Chris-Kawa said in is it possible to override destructor ? what care we have to take when we use it ?:

                            When you expect your class to be derived from and have polymorphic behavior.

                            When you expect your class to be derived from and have polymorphic behavior. <===I think it is better to prepare for the unexpected. When all coders know what to expect, there may not be any bugs anymore. What is the cost of triggering virtual destructor call in a GUI application? In a large project, people can easily embed mines by not setting destructors to be virtual.
                            And often when a destructor is created(needed), programmers want to clear certain things in it. Then I do not understand why not to call it when its parent classes are destroyed.

                            1 Reply Last reply
                            1
                            • C Offline
                              C Offline
                              Chris Kawa
                              Lifetime Qt Champion
                              wrote on 6 Jul 2022, 23:50 last edited by
                              #13

                              What is the cost of triggering virtual destructor call in a GUI application?

                              Well, first of all C++ is not just about GUI applications (it's the minority of them really). But even in GUI apps you can face a task that requires a bunch of objects destroyed, for example point clouds, large number of database entries etc. It adds up. It might not mean much in a calculator app, but you mentioned good habits, so one of them is minding performance, even if it's not the most critical aspect of given task.

                              I think it is better to prepare for the unexpected

                              You can't, if you do it becomes expected :)
                              In all seriousness defensive programming has its uses of course, but it depends on your priorities. In mission critical software it might be desirable but in high performance or energy conservative scenarios it is the worst. And who likes laggy or battery eating apps? ;)

                              J 1 Reply Last reply 7 Jul 2022, 13:47
                              2
                              • Q Qt embedded developer
                                6 Jul 2022, 14:37

                                @JonB I heard from many place that in c++ constructor overriding not possible.

                                K Offline
                                K Offline
                                Kent-Dorfman
                                wrote on 7 Jul 2022, 00:33 last edited by
                                #14

                                @Qt-embedded-developer said in is it possible to override destructor ? what care we have to take when we use it ?:

                                I heard from many place that in c++ constructor overriding not possible.

                                This is just untrue. Any time you subclass something you have a choice when you create the subclass constructor: ignore the base class constructor (usually a bad idea) or add the base class constructor in the initializer list.

                                struct base {
                                explicit base() {}
                                };
                                struct subclass: public base {
                                explicit subclass(): base() {} // calls base() then does subclass initialization
                                };
                                
                                1 Reply Last reply
                                1
                                • S Offline
                                  S Offline
                                  SimonSchroeder
                                  wrote on 7 Jul 2022, 07:08 last edited by
                                  #15

                                  Well, you can't override a constructor or destructor in the same way you override a regular member function. For member functions overriding means to completely replace the function. If you want to include the behavior of the member function in the super class you have to be explicit. For constructors and destructors a call to the super class happens implicitly. So, in this sense you cannot override constructors or destructors. It depends on your definition.

                                  Another way of looking at this is that with overridden member functions – and also destructors – you can use a pointer to the base class to call them. In this sense constructors cannot be overridden. If you call the constructor of the base class, how should the compiler know to call a constructor of a derived class? Let alone how should the compiler know of which derived class to call the constructor if there are multiple derived classes. From this point of view constructors can (fortunately!!!) not be overridden (in C++).

                                  @Qt-embedded-developer said in is it possible to override destructor ? what care we have to take when we use it ?:

                                  what we have to take care when we override destructor ?

                                  You have to be careful when you don't override the destructor. If you actually override the destructor everything will work as it should. If you forget, however, to override the destructor weird things can happen if you really should've overridden it.

                                  J K 2 Replies Last reply 7 Jul 2022, 07:40
                                  2
                                  • S SimonSchroeder
                                    7 Jul 2022, 07:08

                                    Well, you can't override a constructor or destructor in the same way you override a regular member function. For member functions overriding means to completely replace the function. If you want to include the behavior of the member function in the super class you have to be explicit. For constructors and destructors a call to the super class happens implicitly. So, in this sense you cannot override constructors or destructors. It depends on your definition.

                                    Another way of looking at this is that with overridden member functions – and also destructors – you can use a pointer to the base class to call them. In this sense constructors cannot be overridden. If you call the constructor of the base class, how should the compiler know to call a constructor of a derived class? Let alone how should the compiler know of which derived class to call the constructor if there are multiple derived classes. From this point of view constructors can (fortunately!!!) not be overridden (in C++).

                                    @Qt-embedded-developer said in is it possible to override destructor ? what care we have to take when we use it ?:

                                    what we have to take care when we override destructor ?

                                    You have to be careful when you don't override the destructor. If you actually override the destructor everything will work as it should. If you forget, however, to override the destructor weird things can happen if you really should've overridden it.

                                    J Offline
                                    J Offline
                                    JonB
                                    wrote on 7 Jul 2022, 07:40 last edited by
                                    #16

                                    @SimonSchroeder said in is it possible to override destructor ? what care we have to take when we use it ?:

                                    It depends on your definition.

                                    Yes, this is my feeling, as a I wrote earlier. It gets tricky with definitions. "Overriding" constructor or destructor is certainly a bit different from any other method.

                                    Having read about it and thought about it now, I think/suspect that the actual answer is: you can override destructor but not constructor.

                                    I base this on two things:

                                    • You override where you can write the keyword override. Simplez. That applies for destructor but not for constructor.

                                    • You have a vtable entry to override. During constructor there simply is no vtable entry set up yet.

                                    I maintain that conceptually you should just think of a derived class's constructors & destructor in terms of overriding, in that you can provide your own code. And although you do not call the base destructor explicitly it, and the base constructor, run implicitly, so you at least have to think about that.

                                    1 Reply Last reply
                                    1
                                    • kkoehneK Offline
                                      kkoehneK Offline
                                      kkoehne
                                      Moderators
                                      wrote on 7 Jul 2022, 07:45 last edited by
                                      #17

                                      Another way of looking at this is that with overridden member functions – and also destructors – you can use a pointer to the base class to call them. In this sense constructors cannot be overridden.

                                      I think this is spot on. If you check out the actual C++ standard, it uses the word 'override' only in the context of virtual methods. And destructors can be virtual, while constructors can't.

                                      Check out e.g.§ 11.7.2, "Virtual Methods" of the latest the C++ standard (emphasis all mine):

                                      A non-static member function is a virtual function if it is first declared with the keyword virtual or if it *overrides* a virtual member function declared in a base class.
                                      

                                      and then later on

                                      Even though destructors are not inherited, a destructor in a derived class *overrides* a base class destructor declared virtual.
                                      

                                      Director R&D, The Qt Company

                                      1 Reply Last reply
                                      4
                                      • J JoeCFD
                                        6 Jul 2022, 15:10

                                        @Qt-embedded-developer add virtual to all of your destructors and make it a habit.

                                        J Online
                                        J Online
                                        J.Hilk
                                        Moderators
                                        wrote on 7 Jul 2022, 08:12 last edited by
                                        #18

                                        @JoeCFD said in is it possible to override destructor ? what care we have to take when we use it ?:

                                        @Qt-embedded-developer add virtual to all of your destructors and make it a habit.

                                        oh no don't do that,

                                        in fact I would go so far and say: Do not add a destructor at all, if you do not need it! It can and will lead to unnecessary overhead, errors, and inefficient code.

                                        Same as with copy/move constructors/assignment operators. If you don't do anything really fancy in them, let it default and therefore let the compiler handle it. I will be much better :p


                                        Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                        Q: What's that?
                                        A: It's blue light.
                                        Q: What does it do?
                                        A: It turns blue.

                                        J 1 Reply Last reply 7 Jul 2022, 14:04
                                        1
                                        • C Chris Kawa
                                          6 Jul 2022, 23:50

                                          What is the cost of triggering virtual destructor call in a GUI application?

                                          Well, first of all C++ is not just about GUI applications (it's the minority of them really). But even in GUI apps you can face a task that requires a bunch of objects destroyed, for example point clouds, large number of database entries etc. It adds up. It might not mean much in a calculator app, but you mentioned good habits, so one of them is minding performance, even if it's not the most critical aspect of given task.

                                          I think it is better to prepare for the unexpected

                                          You can't, if you do it becomes expected :)
                                          In all seriousness defensive programming has its uses of course, but it depends on your priorities. In mission critical software it might be desirable but in high performance or energy conservative scenarios it is the worst. And who likes laggy or battery eating apps? ;)

                                          J Offline
                                          J Offline
                                          JoeCFD
                                          wrote on 7 Jul 2022, 13:47 last edited by
                                          #19

                                          @Chris-Kawa Got it. Qt uses virtual destructors all over the places across the framework. So it may be a laggy or battery eating apps. You are a Qt moderator. Are we still good?

                                          C S 2 Replies Last reply 7 Jul 2022, 15:05
                                          0
                                          • J J.Hilk
                                            7 Jul 2022, 08:12

                                            @JoeCFD said in is it possible to override destructor ? what care we have to take when we use it ?:

                                            @Qt-embedded-developer add virtual to all of your destructors and make it a habit.

                                            oh no don't do that,

                                            in fact I would go so far and say: Do not add a destructor at all, if you do not need it! It can and will lead to unnecessary overhead, errors, and inefficient code.

                                            Same as with copy/move constructors/assignment operators. If you don't do anything really fancy in them, let it default and therefore let the compiler handle it. I will be much better :p

                                            J Offline
                                            J Offline
                                            JoeCFD
                                            wrote on 7 Jul 2022, 14:04 last edited by JoeCFD 7 Jul 2022, 14:04
                                            #20

                                            @J-Hilk I agree with you that do not add a destructor if it is not needed. But when it is needed, I would prefer to make it virtual.

                                            1 Reply Last reply
                                            0

                                            9/26

                                            6 Jul 2022, 16:15

                                            topic:navigator.unread, 17
                                            • Login

                                            • Login or register to search.
                                            9 out of 26
                                            • First post
                                              9/26
                                              Last post
                                            0
                                            • Categories
                                            • Recent
                                            • Tags
                                            • Popular
                                            • Users
                                            • Groups
                                            • Search
                                            • Get Qt Extensions
                                            • Unsolved