A a = *(A *)new B(); a.func();
Here, what happens in this code, step by step:
new B() : a new object of type B is allocated in free storage, resulting in its address(A*) : the address of the object is added to A* , so we have a pointer of type A* , which actually points to an object of type B that is valid. All OK.A a : here the problems begin. A new local object of type A is created on the stack and created using the copy constructor A::A(const A&) , the first parameter being the object created earlier.- The pointer to the original object of type B is lost after this statement, which leads to a memory leak, since it was allocated in free storage using
new . a.func() - the method is called in the (local) object of class A.
If you change the code to:
A& a = *( A*) new B(); a.func();
then only one object will be created, its pointer will be converted to a pointer of type A* , then dereferenced, and a new link will be initialized using this address . Then the call to the virtual function will be dynamically resolved to B::func() .
But remember that you still need to free the object since it was allocated with new :
delete &a;
Which, incidentally, will only be correct if A has a virtual destructor for which B :: ~ B () is required (which, fortunately, is empty here, but in the general case it is not necessary) will also be called. If A does not have a virtual destructor, then you need to free it:
delete (B*)&a;
If you want to use a pointer, then this is the same as with a link. The code:
A* a = new B();
Kos
source share