Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Oct 3, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Base Virtual Function To Determine Overridden Functions

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.

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:

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






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date