Dmitri Islentyev wrote:
Hello everyone!
Please consider the following code:
class Base {
public:
Base(int x);
virtual int foo() { return 17; }
};
class Derived: public Base {
Derived(int x);
int foo() { return 23; }
};
class Maker {
static Base CreateBase(bool whether)
{
if(whether)
return Base(0);
else
return Derived(1);
}
};
This function creates either a Base or a Derived, and then will make a
copy of the Base part of it and return that. This is called slicing.
Since the return type is Base, it's _always_ a Base that is returned.
// client
Base b=Maker.CreateBase(1);
b.foo(); // returns 17
Base d=Maker.CreateBase(0);
d.foo(); // returns 17
There`s no vtable in value variables, the solution is to use pointers.
No, that doesn't have to do with the vtable. The problem is the slicing
that I mentioned above.
Btw: the values of bool are true and false. 1 and 0 will be converted to
true and false, but it's more clear to write true and false directly.
But what`s the method to delete returned pointers, if, for example,
I return a cursor class from operator [] just for one function call
from returned cursor instance?
I'm not sure what exactly you mean. In your above example, you could
allocate your object with new and return a pointer to it. Then the
caller will be responsible for deleting the object. Another solution is
a smart pointer like boost::shared_ptr, which is a reference counted
smart pointer class. It will automatically delete the object if no
shared_ptr points to it anymore.