S
Steven Powers
Imagine the following setup
class Parent
{
virtual void doStuff();
}
class Child : public Parent
{
virtual void doStuff();
}
and this function
bool foo(Parent *p)
{
if(!p)
p = new Parent();
p->doStuff();
}
I would like foo() to take a pointer and if it is null allocate the
memory for the class I pass in.
For example
Child * c = NULL;
foo(c);
would result in a Child() constructor and Child::doStuff() being
called.
The way it is now Parent() and Parent::doStuff() will get called.
How can this be done while keeping foo defined as foo(Parent *p) ????
I've thought of using templates like this:
template<class T>
bool foo(Parent* p)
{
if(!p) p = new T();
p->doStuff();
}
but I am unable to get the correct type from a second templated class
that has been passed T = Child* as its template type.
As a follow up can I get a template value T = Child* and somehow pass
foo T=Child ???
class Parent
{
virtual void doStuff();
}
class Child : public Parent
{
virtual void doStuff();
}
and this function
bool foo(Parent *p)
{
if(!p)
p = new Parent();
p->doStuff();
}
I would like foo() to take a pointer and if it is null allocate the
memory for the class I pass in.
For example
Child * c = NULL;
foo(c);
would result in a Child() constructor and Child::doStuff() being
called.
The way it is now Parent() and Parent::doStuff() will get called.
How can this be done while keeping foo defined as foo(Parent *p) ????
I've thought of using templates like this:
template<class T>
bool foo(Parent* p)
{
if(!p) p = new T();
p->doStuff();
}
but I am unable to get the correct type from a second templated class
that has been passed T = Child* as its template type.
As a follow up can I get a template value T = Child* and somehow pass
foo T=Child ???