A Function that has a return type of a parent class returning its child

I have a parent class and want a function that returns an object that is a type of one of its children. Is this possible to do in C++? As of right now I have a function that tells what type needs to be returned than have different functions for each type and then each child class has its own function based on that type.
1
2
3
4
5
6
  Parent foo()
  {
     if (condition)
        return child1(); //Return an object of type child1
     return child2();    //Return an object of type child2
  }

On an aside, is it possible for a function in the parent class to call a function that is only present in the child class?

Thank you!
Is this possible to do in C++?
Yes. You need to use pointers for object oriented programming (as you do in every other language).
1
2
3
4
5
6
7
Parent* func()
{
    if (condition())
        return new child1();

    return new child2();
}
That helped a lot! Thank you.
It did lead to one more problem though. I need it to call methods from the child class; however, when I try I get the error message that the function is not a member of the parent class. How would I make it look in the child class for the function instead? Again, thank you so much.
Topic archived. No new replies allowed.