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.
#ifndef POLYTEST_H #define POLYTEST_H class polyTest { public: polyTest(); virtual void type(); virtual ~polyTest(); }; #endif #include "polyTest.h" #include <iostream> using namespace std; void polyTest::type() { cout << "first gen"; } #ifndef POLYCHILD_H #define POLYCHILD_H #include "polyTest.h" using namespace std; class polyChild: public polyTest { public: void type(); }; #endif #include "polyChild.h" #include <iostream> void polyChild::type() { cout << "second gen"; } #include <iostream> #include "polyChild.h" #include "polyTest.h" int main() { polyTest * ptr1; polyTest * ptr2; ptr1 = new polyTest(); ptr2 = new polyChild(); ptr1 -> type(); ptr2 -> type(); return 0; } I realized that I didn't implement the constructor or the destructor, because this is just a test class, they don't have to do anything, and that the compiler would provide with a default constructor/destructor. Would that be why I'm getting compilation errors? And why would that be the case?
polyTestdefault ctor but you have not defined it.std::unique_ptr<polyTest> ptr1(new PolyTest());if you want automated clean-up.