Reputation: 614
So here's my code I'm working with:
#include <iostream>
class Node
{
public:
void speak(){std::cout << "I'm a base node" << std::endl;}
};
class Child : public Node
{
public:
void speak(){std::cout << "I'm a child node" << std::endl;}
};
int main()
{
Node node;
Child child;
node.speak();
child.speak();
std::cout << "= Pointers..." << std::endl;
Node* pnode = &node;
Node* pchild = &child;
pnode->speak();
pchild->speak();
}
And here's the output:
I'm a base node
I'm a child node
= Pointers...
I'm a base node
I'm a base node
The pchild->speak();
calls the Node
's method and not the Child
's one.
Now my problem is that I may have many different types of nodes, with varying number of connections. Thus I cannot declare a member pointer with a ChildX
class, but only with a generic Node
class. But each node will have a certain method that I want called.
I've tried to have a pointer to that method itself instead of to the class (since it would always be int (*foo)()
type), but the compiler complains about invalid use of non-static member function
.
So both of my approaches don't work. Neither pointer to a class, nor pointer to classes member function.
Upvotes: 0
Views: 34
Reputation: 25895
Familiarize yourself with virtual functions and polymorphism - both key concepts in c++.
In your question you simply need to define
virtual void speak(){std::cout << "I'm a base/child node" << std::endl;}
Upvotes: 1