C ++ virtual function
- by user2950788
masters of C++.
I am trying to implement polymorphism in C++. I want to write a base class with a virtual function and then redefine that function in the child class. then demonstrate dynamic binding in my driver program. But I just couldn't get it to work.
I know how to do it in C#, so I figured that I might have made some syntactical mistakes where I had used C#'s syntax in my C++ code, but these mistakes are not obvious to me at all. So I'd greatly appreciate it if you would correct my mistakes.
class polyTest
{
public:
polyTest();
virtual void type();
virtual ~polyTest();
};
void polyTest::type()
{
cout << "first gen";
}
class polyChild: public polyTest
{
public:
void type();
};
void polyChild::type()
{
cout << "second gen";
}
int main()
{
polyChild * ptr1;
polyChild * ptr2;
ptr1 = new polyTest();
ptr2 = new polyChild();
ptr1 -> type();
ptr2 -> type();
}