Rather than a long explanation, I think a few lines of code will be clearer to explain my problem. Lets say I have 2 classes, one inheriting from the other :
#include <iostream>
class A{
public:
void parse()
{
treatLine();
};
void treatLine()
{
std::cout << "treatLine in A" << std::endl;
}
};
class B : public A{
public:
void treatLine()
{
std::cout << "treatLine in B" << std::endl;
}
};
int main()
{
B b;
b.parse();
return 0;
}
When executing, surprisingly for me, it prints “treatLine in A”. Is it possible to make function treatLine from class B to be called whith an object of type B (ie “treatLine in B” would be print for the code above)? And keep the possibility of creating an object of type A that would print “treatLine in A”
Make
treatLinevirtual:That way, the function will be called based on the runtime type of the object (called the “dynamic type”), instead of the compiletime type (called the “static type”) of the object.