c++virtual

C++ want to call derived function from base class


I have following situation

class base
{
public:

   virtual void Accepted(SOCKET s)  //// Event
   {

   }
   void Listner()
   {
          SOCKET acpted;
          Accepted(acpted); /// When I call I want derived class's Accepted() to get called

   }

};


class derived
{
   virtual void Accepted(SOCKET s)  //// Event
   {
         ////// HERE i will write actual implementation (QUESTION)
   }

}

I want to call derived class's function. This will work like event here. I want to notify derived class that something happened in base class.


Solution

  • class derived : public base will make derived actually inherit from base. Then your virtual function call will work as expected.

    Note that you cannot make such virtual function calls in the constructor or destructor of base - At the time base's constructor is invoked, the derived part doesn't yet exist. At the time base destructor is invoked, the derived part has already been destructed.

    EDIT: Demo, in response to comment.

    class base
    {
    public:
        virtual void Accepted(SOCKET s)  //// Event
        {
            cout << "base::Accepted" << endl;
        }
        void Listner()
        {
            SOCKET acpted = 0;
            Accepted(acpted); /// When I call I want derived class's Accepted() to get called
        }
    };
    
    
    class derived : public base
    {
        virtual void Accepted(SOCKET s)  //// Event
        {
            cout << "derived::Accepted" << endl;
        }
    };
    
    
    int main(int argc, char * argv[])
    {
      derived d;
        d.Listner();
    }
    

    This will print derived::Accepted