R. Clayton (rclayton@monmouth.edu)
(no date)
Does there exist a concept of virtual constructors in C++? If yes in what
situations are they used.
No. The dynamic type of value is the name of the constructor (that is, the
name of the class), so you'd end up at the same place anyway.
The closest you could get, depending on what you mean by virtual, is the
factory pattern. You use the factory pattern whenever you need a polymorphic
constructor; that is, a constructor that can return one of set of related class
instances.
For example, in client-server computing, the server can receive one of a number
of different kind of messages, but the messages are all related to the service
being provided. One way to model this is to is to create a service-message
parent and have each particular message be a child:
class server_msg { ... }
class server_msg_hello : server_msg { ... }
class server_msg_goodbye : server_msg { ... }
class server_msg_request : server_msg { ... }
and so on. What I'd like is a server_msg constructor that takes a packet read
from the network and turns it into a message of the proper kind, but it's not
possible to do that in the server_msg constructor, which can only return a
server_msg.
What you can do instead is create a server-message factory that examines the
packet and calls the appropriate child constructor:
server_msg server_msg::
server_msg_factory(const byte packet[])
if (is_hello_msg(packet))
return server_msg_hello(packet)
if (is_goodbye_msg(packet))
return server_msg_goodbye(packet)
// and so on.
server_msg_factory() is now a virtual constructor (in some sense) because it
calls the appropriate constructor based on the dynamic type (in some sense) of
the packet.
This archive was generated by hypermail 2.0b3 on Mon May 03 2004 - 17:00:06 EDT