0% found this document useful (0 votes)
58 views

Virtual Constructors

Memory leak occurs when memory is allocated to an object but there is no pointer referring to it, so the memory cannot be deleted or reused. A dangling pointer points to an object that no longer exists. Virtual calls allow calling a function knowing only an interface, not the exact object type, but constructors require knowing the exact type to create an object. Techniques like factories can provide an indirect way to create objects similar to virtual constructors.

Uploaded by

api-3825559
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Virtual Constructors

Memory leak occurs when memory is allocated to an object but there is no pointer referring to it, so the memory cannot be deleted or reused. A dangling pointer points to an object that no longer exists. Virtual calls allow calling a function knowing only an interface, not the exact object type, but constructors require knowing the exact type to create an object. Techniques like factories can provide an indirect way to create objects similar to virtual constructors.

Uploaded by

api-3825559
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

What is Memory Leak?

Memory which has no pointer pointing to it and there is no way to delete or reuse this
memory(object), it causes Memory leak.
{
Base *b = new base();
}
Out of this scope b no longer exists, but the memory it was pointing to was not deleted.
Pointer b itself was destroyed when it went out of scope.
What is Dangling Pointer?
A pointer which is pointing to an object which no longer exists is a dangling pointer.
MyClass* p(new MyClass);
MyClass* q = p;
delete p;
p->DoSomething(); // Watch out! p is now dangling!
p = NULL; // p is no longer dangling
q->DoSomething(); // Ouch! q is still dangling!
Why don't we have virtual constructors?
A virtual call is a mechanism to get work done given partial information. In particular,
"virtual" allows us to call a function knowing only an interfaces and not the exact type of
the object. To create an object you need complete information. In particular, you need to
know the exact type of what you want to create. Consequently, a "call to a constructor"
cannot be virtual.
Techniques for using an indirection when you ask to create an object are often referred to
as "Virtual constructors". For example, see TC++PL3 15.6.2.

You might also like