J
James Brown
I have two classes, a base class, and a
class base
{
public:
base();
virtual void foo() = 0;
};
class derived : public base
{
public:
derived();
void foo();
void foo2();
};
Due to existing design, I also have a function which basically does:
base *create_object()
{
return new derived; // Q1. Do I need a cast here?
}
i.e.
base *object = create_object();
Now, I have a requirement to call a non-virtual function in the derived
class,
even though I have a pointer to the case class:
i.e.
derived *object2 = static_cast<derived *>object;
object2->foo2();
So my two questions:
1. In the create_object function, do I need a cast to "downcast" from
derived -> base?
2. Assuming that I can guarantee that create_object *always* returns a
"derived" object
(even though it returns a pointer-to-base), is it safe to cast back to
the derived class?
p.s. I want to avoid using dynamic_cast due to runtime requirements.
So basically I need to know if:
base = derived;
derived = base;
is a safe operation?
TIA
James
class base
{
public:
base();
virtual void foo() = 0;
};
class derived : public base
{
public:
derived();
void foo();
void foo2();
};
Due to existing design, I also have a function which basically does:
base *create_object()
{
return new derived; // Q1. Do I need a cast here?
}
i.e.
base *object = create_object();
Now, I have a requirement to call a non-virtual function in the derived
class,
even though I have a pointer to the case class:
i.e.
derived *object2 = static_cast<derived *>object;
object2->foo2();
So my two questions:
1. In the create_object function, do I need a cast to "downcast" from
derived -> base?
2. Assuming that I can guarantee that create_object *always* returns a
"derived" object
(even though it returns a pointer-to-base), is it safe to cast back to
the derived class?
p.s. I want to avoid using dynamic_cast due to runtime requirements.
So basically I need to know if:
base = derived;
derived = base;
is a safe operation?
TIA
James