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 call virtual function in constructor ? why we have to not use it in constructor ?
Forum Updated to NodeBB v4.3 + New Features

is it possible to call virtual function in constructor ? why we have to not use it in constructor ?

Scheduled Pinned Locked Moved Unsolved C++ Gurus
3 Posts 3 Posters 702 Views 3 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.
  • Q Offline
    Q Offline
    Qt embedded developer
    wrote on 4 Jul 2022, 09:22 last edited by
    #1

    I wan to know pros and cons of virtual function use in constructor. i want to know it with real time example.

    1 Reply Last reply
    0
    • S Offline
      S Offline
      sierdzio
      Moderators
      wrote on 4 Jul 2022, 09:55 last edited by
      #2

      Pros: none.

      Cons: it's dangerous, don't do it! Many compilers will warn you against it.

      https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors

      https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors

      (Z(:^

      1 Reply Last reply
      5
      • C Offline
        C Offline
        Chris Kawa
        Lifetime Qt Champion
        wrote on 4 Jul 2022, 11:08 last edited by
        #3

        Pros: Using it can start interesting conversations with your reviewers

        Cons: Dangerous, easy to get wrong, if you get it right it's easy to forget and break later, genuine "gotcha", like the spanish inquisition - nobody expects it.

        Example:

        class Base
        {
        public:
            Base() { foo(); }
            void something() { foo(); }
        
            virtual void foo() {}
        };
        
        class Derived : public Base
        {
        public:
           void foo() override {}
        };
        
        int main()
        {
            Derived instance;     // calls Base::foo()
            instance.something(); // calls Derived::foo()
        }
        

        That's the easiest gotcha and a bug waiting to happen. Usually it's hidden in a lot more code surrounding it and not that easy to spot. With a complicated inheritance structure you could even end up calling a pure virtual base function and that would crash your app.

        1 Reply Last reply
        5

        2/3

        4 Jul 2022, 09:55

        • Login

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