devxlogo

Base Virtual Function To Determine Overridden Functions

Base Virtual Function To Determine Overridden Functions

Question:
I am using VC++ 5.0, and have a base class with several virtual functions. The derived class may/may not implement the function. If it does, it first calls the base function explicitly and then continues with any custom code. The base function is opening a socket for communication, leaving it open, and the derived function will continue to use the channel. If there isn’t an implemented derived function, the base is getting called directly and leaving the socket open. I would like to know if there is a way that the base function can inspect the “this” pointer to determine if its associated object has an overriding function, and if not close the connection. Aside from the C++ morality issue, I want to implement this in the base class so that the numerous derived classes are kept simple.

Answer:
Having a base class examine the actual type of a derived object is never a good idea. What happens if at a later stage you decide to add an extra level of derivation? You will need to change the base class’s code so that it knows how to handle its grandson class. There is another problematic issue here: your base class’s virtual functions open sockets even if these sockets aren’t used at all. This is inefficient and can cause unpleasant surprises at runtime, as the number of available sockets is limited. It seems like you need to redesign your class hierarchy. Instead of having virtual functions that open and close sockets at the base class, make these functions pure virtual (or empty functions that don’t perform any operation) and have the derived class implement the functionality. Because the derived class knows when it needs to write to a socket, it should be the one that opens and closes that socket. To simplify the implementation, you can add another auxiliary class that has only two member functions: a constructor that opens a socket and destructor that closes that socket. In the derived class member function, create an instance of this auxiliary object:

See also  Why ChatGPT Is So Important Today

void Derived:WriteData(){ if(needs_to_write_data) {  socket s;  Auxiliary aux( &s );  if (s)   {   //.. write to socket  }  else  {   cerr<< "an error occurred";  } } // end if(needs_to_write_data)}//aux is destroyed here and closes the socket}

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist