Is there Virtual Constructor
I had just read that we can create a virtual constructor but where we r using that constructor is not cleared to me. I had searched over web but i cannot get any satisfactory simple example. so you experts can help me in this problem..
Next thing i want to know that why is not possible to create like
class b : public a
aa=new b;///this things r possible.
b *b = new a; /// This is not possible but i am not clear why???
when you declare b* b= new a; (which by the way wouldn't work syntactically anyway , because you try to create a variable with the same name as the class), you make a promise, that your "variable b" points to an instance of "class b". But because you create an instance of class a, which is smaller than an instance of class b you are in trouble (members of b have not enough space...).
Regarding the virtual constructors: I've never heard of them, whichdoesn't mean they don't exist. But what would they do? Would polymorphism make the runtime system only call the constructor of the derived class? Hardly...
Thank you for reply
it was not like b *b = new a but any object like
b *obj_b = new a;//I knew this is not true as b is derived class but i want to know why this is not possible.
Technically speaking, C++ doesn't have virtual constructors for two good reasons:
1) constructors don't have names so you can't call them explicitly.
2) more importantly: in order to call a virtual function, you must have a fully-constructed object. An object is considered fully constructor once its constructor has completed execution without throwing an exception. So you can see the problem here: calling a virtual constructor would require an already constructed object, which can be accomplished by calling a constrcutor etc.
That said, there are several porogramming idioms that sumulate a virtual constrcutor. Here's an example of this:
The Class Factory Design Pattern also offers a similar mechanism.
Your question raises another subject: why B* b = new A
won't compile. Remember that the is-a rlationship applies to derived classes. If D is publicly derived from B, then it's a B. The reverse isn't true though. Would you want to say for example that a CObject class is a CNetworkData class, assuming that the latter is derived from the former? Certainly not.
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL