Created
January 4, 2012 21:05
-
-
Save munro/1562134 to your computer and use it in GitHub Desktop.
Stripping off extended class properties when copying
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 Foo { | |
public: | |
int a; | |
Foo(int a) : a(a) { | |
} | |
virtual void print() { | |
cout << " I am Foo: " << a << "\n"; | |
} | |
}; | |
class Bar : public Foo { | |
public: | |
int b; | |
Bar(int a, int b) : Foo(a), b(b) { | |
} | |
void print() { | |
cout << " I am Bar: " << a << ", " << b << "\n"; | |
} | |
}; | |
int main(int argc, char** argv) { | |
cout << "Initializing Foo & Bar\n"; | |
Foo foo(13); | |
Bar bar(13, 37); | |
foo.print(); // I am Foo: 13 | |
bar.print(); // I am Bar: 13, 37 | |
cout << "Calling &bar as Foo\n"; | |
((Foo*)(&bar))->print(); // I am Bar: 13, 37 | |
cout << "Copying bar to a Foo object, stripping off Bar\n"; | |
((Foo)(bar)).print(); // I am Foo: 13 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment