Skip to content

Instantly share code, notes, and snippets.

@munro
Created January 4, 2012 21:05
Show Gist options
  • Save munro/1562134 to your computer and use it in GitHub Desktop.
Save munro/1562134 to your computer and use it in GitHub Desktop.
Stripping off extended class properties when copying
#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