CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2002
    Posts
    12

    Please help me with this simple program.


    #include <iostream>

    using namespace std;

    class CFather{
    public:
    CFather() { InitInstance(); }
    virtual void InitInstance(){
    cout << "I am the father." << endl;
    }
    };

    class CSon : public CFather{
    public:
    void InitInstance(){
    cout << "I am the son." << endl;
    }
    };

    int main()
    {
    CSon son;
    return 0;
    }



    The program's output is:
    I am the father.

    How can I make the CFather's constructor invoke the InitInstance function defined in the CSon?
    Thanks a lot!


  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: Please help me with this simple program.

    You can't. At the time the CFather ctor is called, the object is not yet a CSon - the vtable hasn't been set up and the virtual function mechanism doesn't work.

    How you get around it depends heavily on what you actually want to do in your InitInstance. Most of the time, virtual init methods are not necessary if your class hierarchy is designed well.

    He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured