Created
February 19, 2016 15:52
-
-
Save wbadart/a8d5c70111f6d62c3764 to your computer and use it in GitHub Desktop.
Shows the applications and behaviors of pure and regular virtual functions. Demonstrates the in-instantiability of abstract classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class AbstractBase{ | |
public: | |
virtual void virtfunc(void) = 0; | |
void regfunc(void); | |
}; | |
class ConcreteBase{ | |
public: | |
// We must implement ConcreteBase::virtfunc in order for this to compile. Try uncommenting the prototype to see what happens | |
// virtual void virtfunc(void); | |
void regfunc(void); | |
}; | |
class AbstractChild:public AbstractBase{ | |
public: | |
virtual void virtfunc(void); | |
}; | |
class ConcreteChild:public ConcreteBase{ | |
public: | |
// virtual void virtfunc(void); | |
}; | |
void AbstractBase::regfunc(void){ | |
cout << "This is a regular function from the abstract base class\n"; | |
} | |
void ConcreteBase::regfunc(void){ | |
cout << "This is a regular function from the concrete base class\n"; | |
} | |
void AbstractChild::virtfunc(void){ | |
cout << "This is the virtual function defined in child class (child of abstract base). Note: this class is iteself concrete.\n"; | |
} | |
// This isn't allowed because we didn't have virtunc in the base class. Mess around with the prototypes or try implementing ConcreteBase::virtfunc to get this working | |
// void ConcreteChild::virtfunc(void){ | |
// cout << "This is the virtual function defined in the child class (child of concrete base).\n"; | |
// } | |
int main(void){ | |
// First we see that we are allowed to instantiate all of the concrete classes: | |
ConcreteBase cBase0; | |
ConcreteChild cChild0; | |
AbstractChild aChild0; //note: I called this class abstract since it inherits from the abstract base. It is iteself a concrete class. | |
// Let's test out some of the functions | |
cBase0.regfunc(); | |
cChild0.regfunc(); | |
// cChild0.virtfunc(); | |
aChild0.regfunc(); | |
aChild0.virtfunc(); | |
// Note that we can't call virtfunc on cBase0, since we didn't implement the function for class ConcreteBase. Try uncommenting the line to see what happens. | |
// cBase0.virtfunc(); | |
// Finally, try uncommenting the line below to check out the compiler error. You'll see that we're not allowed/able to instantiate an abstract class. | |
// AbstractBase aBase0; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment