I see the following problems in your code.
Mismatching function and function pointer
In Parent
, you have defined NewChild
as:
Child (*NewChild)();
That says NewChild
is a pointer to a function that takes no arguments and returns a Child
object.
The function that you have defined:
Child *NewChild() { ...
Takes no arguments and returns a pointer to a Child
, not an object of Child
.
You'll have to decide which one needs to be fixed. To fix the function, make its return type Child
.
Child NewChild() { ...
Uninitialized Child
of parent
You have left the value of parent.Child
uninitialized yet you are trying to use it.
Setting the member of Child
You use the following code to set the name
of child
.
child->name = "foo";
This may or may not be a problem depending on how you use child->name
since child->name
points to some global data in the computers read-only memory. It will be better to make a copy of "foo"
.
Here's my suggestion for updating your code:
Child NewChild()
{
Child child;
// strdup is available on some platforms but it can
// be implemented easily.
child->name = strdup("foo");
return child;
}
int main()
{
Parent parent;
parent.NewChild = NewChild;
Child child = parent.NewChild();
}