c++ virtual function called in constructor
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: c++ virtual function called in constructor

  1. #1
    Join Date
    Apr 2010
    Posts
    1

    Angry c++ virtual function called in constructor

    Hello I have one question in c++. I have a base class B and this has a virtual function f1( )
    and d1, d2 and d3 are the derived classes of the B. Only d3 overrides the virtual function.

    Question : from my B constructor i need to call the function f1( ). For the objects of type d1 and d2 i expect the base class
    versions virtual function be called where as for the objects d3 i am expecting the d3 version of the virtual function being excecuted.



    Class B
    {
    public:
    B( ) { f1( ); }
    virtual void f1( ) { //d1 ,d2 and base use this code}

    }

    Class d1 : public B
    {

    }

    Class d1 : public B
    {

    }

    Class d3 : public B
    {
    virtual f1( ) { //d3 specific code }

    }


    main( )
    {
    B *b1 = new d1( ); /*I expect the base version of the f1() would be called */
    B *b3 = new d3( ); /*I expect the base version of the f1() would be called */

    }

    Can some body please help me in solving this.
    I know when a constructor calls a virtual function , only the current class virtual function would be called. In this case
    only base f1( ) version would be called even for the b3 object.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,276

    Re: c++ virtual function called in constructor

    Calls to member functions in constructors are always non-virtual, so what you are asking for cannot be done, at least not in this way. You can read: When my base class's constructor calls a virtual function on its this object, why doesn't my derived class's override of that virtual function get invoked?
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center