Skip to content

Instantly share code, notes, and snippets.

@DomNomNom
Created August 28, 2014 02:58
Show Gist options
  • Save DomNomNom/d278ca0049202a788e0c to your computer and use it in GitHub Desktop.
Save DomNomNom/d278ca0049202a788e0c to your computer and use it in GitHub Desktop.
Underhanded stuff in C++. No warnings from the compiler
// curtesy of https://github.com/DavidSaxon and http://www.parashift.com/c++-faq-lite/
#include <iostream>
// this function will be called by the base class
void baseFunction() {
std::cout << "Base Class!" << std::endl;
}
// this function will be called by the derived class
void derivedFunction() {
std::cout << "Derived Class!" << std::endl;
}
// just a testing function that nothing ever calls
void shouldNeverBeCalled() {
std::cout << "Nope!" << std::endl;
}
// base class
class Base {
public:
// constructor
Base() {
// point the function variable to the base function
function = &baseFunction;
}
// pointer to a function
void (*function)();
};
// derived class
class Derived : public Base {
public:
// constructor
Derived() {
// point the function variable to the derived function
function = &derivedFunction;
// put the address of the function into this extra variable since it's
// feeling lonely and wants something to do
i = (long) function;
}
long i;
};
// this calls the function on the second item in the given array
void callFunctionOnArray(Base* base) {
base[1].function();
}
// main function
int main() {
std::cout << std::endl;
std::cout << "-------------------------------------------------------------"
"-------------------"
<< std::endl;
std::cout << std::endl;
std::cout << "Will the base or derived class function be called?"
<< std::endl;
std::cout << std::endl;
// make an array of the derived class
Derived arrayOfDerived[10];
// check the elements are definitely of type Derived by attempting to access
// the extra variable which the derived class has (it doesn't matter that we
// are messing with it since the first element in the array is never used)
arrayOfDerived[0].i += 34;
// should print 'derived function' right?
callFunctionOnArray(arrayOfDerived);
std::cout << std::endl;
std::cout << "-------------------------------------------------------------"
"-------------------"
<< std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment