The following is my code,
#include<iostream>
#include<string>
using namespace std;
class TestClass
{
public:
virtual void test(string st1, string st2);
};
class ExtendedTest: public TestClass
{
public:
virtual void test(string st1, string st2);
};
void TestClass::test(string st1, string st2="st2")
{
cout << st1 << endl;
cout << st2 << endl;
}
void ExtendedTest::test(string st1, string st2="st2")
{
cout << "Extended: " << st1 << endl;
cout << "Extended: " << st2 << endl;
}
void pass(TestClass t)
{
t.test("abc","def");
}
int main()
{
ExtendedTest et;
pass(et);
return 0;
}
When I run the code, the method(‘test’) of base class is called.
But I expect the method of child is called because I specified methods as virtual function.
Then how can I make method of child class be called ? Thank you.
When you do this, the object you are passing gets sliced into a
TestClassand its identity is lost, so it now behaves like aTestClassand calls the method accordingly.To Fix this you want to pass
tby reference as @Nick suggested, or (not recommended) by pointer. It will now retain its identity and call the appropriate function, as long astestis marked virtualEdit: fixed spliced -> sliced .. too much bioshock..