Skip to content

Instantly share code, notes, and snippets.

@mike10004
Last active June 19, 2020 15:53
Show Gist options
  • Save mike10004/902ea9c73d30179ea08c8fbb045cf59d to your computer and use it in GitHub Desktop.
Save mike10004/902ea9c73d30179ea08c8fbb045cf59d to your computer and use it in GitHub Desktop.
Classes and slicing in C++

Because I always forget this stuff, I'm putting it here.

Output of program:

cool
cool
cool
not cool

Because slicing ain't cool.

#include <iostream>
using namespace std;
class A {
public:
A() = default;
virtual ~A() = default;
virtual void Talk() const {
cout << "not cool" << endl;
}
};
class B : public A {
public:
B() = default;
~B() override = default;
void Talk() const override {
cout << "cool" << endl;
}
};
int main()
{
B thing;
A* ptr = &thing;
A& ref = thing;
A slice = thing;
thing.Talk();
ptr->Talk();
ref.Talk();
slice.Talk();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment