C++ polymorphism, function calls
- by moai
Okay, I'm pretty inexperienced as a programmer, let alone in C++, so bear with me here. What I wanted to do was to have a container class hold a parent class pointer and then use polymorphism to store a child class object. The thing is that I want to call one of the child class's functions through the parent class pointer. Here's a sort of example of what I mean in code:
class SuperClass
{
public:
int x;
}
class SubClass : public SuperClass
{
public:
void function1()
{
x += 1;
}
}
class Container
{
public:
SuperClass * alpha;
Container(SuperClass& beta)
{
alpha = beta;
}
}
int main()
{
Container cont = new Container(new SubClass);
}
(I'm not sure that's right, I'm still really shaky on pointers. I hope it gets the point across, at least.)
So, I'm not entirely sure whether I can do this or not. I have a sneaking suspicion the answer is no, but I want to be sure. If someone has another way to accomplish this sort of thing, I'd be glad to hear it.