I have a polymorphic class hierarchy. Although I also support the standard factory approach, where I use only base class pointers, I also need a factory mechanism that gives me derived classes, which is not so simple because these functions differ only in their return types. That's why I came up with the idea of overloading a function and letting the compiler choose the right one.
A simple application is that I can write functions that create a derived object, "prepare" it, and return a base pointer to it for future access when type information is no longer needed.
- Question 1: Is the following:
- Question 2: The newObject () parameter is intended only for the compiler to select the correct function. I am worried about using
p1
the same line where it is declared. I have never read its value before setting it to newObject()
, but I'm not sure if this can cause undefined behavior. I also have self-determination, because the return value is assigned to itself ...
This is a sample code:
class Base
{
public:
virtual ~Base(void){}
};
class Derived1 : public Base
{
public:
virtual ~Derived1(void){}
};
class Derived2 : public Base
{
public:
virtual ~Derived2(void){}
};
Base * newObject(int i)
{
if (i == 1)
{
return new Derived1();
}
else
{
return new Derived2();
}
}
Derived1 * newObject(Derived1 *& p)
{
p = new Derived1();
return p;
}
Derived2 * newObject(Derived2 *& p)
{
p = new Derived2();
return p;
}
int main()
{
Derived1 * p1 = newObject(p1);
Derived2 * p2 = newObject(p2);
Derived2 * p3 = nullptr;
newObject(p3);
delete p3;
delete p2;
delete p1;
}
EDIT:
To get around the problem of using a newly created variable, this is an alternative:
Derived1 * newObject(Derived1 *)
{
Derived1 * p = new Derived1();
return p;
}
source
share