+ Reply to Thread
Results 1 to 2 of 2

Thread: Calling virtual function from Constructor

  1. #1
    admin's Avatar
    admin is offline Administrator
    Join Date
    Mar 2010
    Posts
    44

    Calling virtual function from Constructor

    What happens if we call virtual function from constructor?

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    Yes, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, "base before derived".

    Consider:
    Code:
    #include<string>
    #include<iostream>
    using namespace std;
    
    class B {
    public:
        B(const string& ss) { cout << "B constructor\n"; f(ss); }
        virtual void f(const string&) { cout << "B::f\n";}
    };
    
    class D : public B {
    public:
        D(const string & ss) :B(ss) { cout << "D constructor\n";}
        void f(const string& ss) { cout << "D::f\n"; s = ss; }
    private:
        string s;
    };
    
    int main()
    {
        D d("Hello");
    }
    the program compiles and produce
    Code:
    B constructor
    B::f
    D constructor
    Note not D::f. Consider what would happen if the rule were different so that D::f() was called from B::B(): Because the constructor D::D() hadn't yet been run, D::f() would try to assign its argument to an uninitialized string s. The result would most likely be an immediate crash.

    Destruction is done "derived class before base class", so virtual functions behave as in constructors: Only the local definitions are used - and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.
    Last edited by surfer; 30th June 2010 at 22:08.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. How does virtual function works
    By Surfer in forum C++ Fundamentals
    Replies: 1
    Last Post: 8th June 2010, 16:37
  2. Virtual Constructor
    By TopGun in forum C++ Fundamentals
    Replies: 0
    Last Post: 13th June 2008, 12:41
  3. What is a virtual member function?
    By TopGun in forum C++ Fundamentals
    Replies: 0
    Last Post: 17th February 2008, 17:09

Tags for this Thread

Bookmarks

Posting Permissions

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