I think have a good feel to this based on my research but would like confirmation. I've been learning about inheritance and how virtual methods work.
In the code at the bottom, I get the results (above code) when running main. If I switch the printType method to be the non-virtual, I instead get "AbstractClass" printing out.
As I understand it, using "virtual" indicates the method might be overwritten - and to always choose the "last reimplementation" of the method, in this case in ImplementationClass. My questions are:
1) Does this ALWAYS happen? Or are there instances where you may end up with the method from AbstractClass (or other classes, if it's inherited multiple times) being called even though it's a virtual method?
2) it seems you cannot instantiate a non-pointer of a class containing virtual methods. Is this true?
3) I am assuming there is nothing different in my two examples, but I'm only about 80% sure.
Many thanks for help, this whole virtual method thing is complicated to figure out from reading (which is why I created a dummy project in the first place!).
after redefinition
ImplementationClass
printing from virtual method in ImplementationClass
second set of examples
ImplementationClass
printing from virtual method in ImplementationClass
#include <iostream>
using namespace std;
class AbstractClass{
public:
virtual void printStuff() = 0;
AbstractClass() {};
~AbstractClass() {};
virtual void printType() { std::cout << "AbstractClass" << std::endl; }
// void printType() { std::cout << "AbstractClass" << std::endl; }
};
class ImplementationClass : public AbstractClass {
public:
void printStuff() { std::cout << "printing from virtual method in ImplementationClass" << std::endl;}
void printType() { std::cout << "ImplementationClass" << std::endl; }
void printStuffOnlyInDerived() {std::cout << "printing from NONvirtual method in ImplementationClass" << std::endl;}
ImplementationClass() {};
~ImplementationClass() {};
};
int main () {
AbstractClass * absClass;
ImplementationClass * impClass= new ImplementationClass;
absClass = impClass;
printf("\nafter redefinition \n");
absClass->printType();
absClass->printStuff();
AbstractClass * absClassNonPtrImpClass = new ImplementationClass;
printf("\n second set of examples \n");
absClassNonPtrImpClass->printType();
absClassNonPtrImpClass->printStuff();
return 0;
}