Skip to content

Instantly share code, notes, and snippets.

@shubham7298
Created February 11, 2020 13:37
Show Gist options
  • Save shubham7298/26a679912f0431f4b0ebcd885115371a to your computer and use it in GitHub Desktop.
Save shubham7298/26a679912f0431f4b0ebcd885115371a to your computer and use it in GitHub Desktop.
Virtual functions in C++
#include <iostream>
using namespace std;
class Base {
public:
void f1() {
cout<<"f1 from base class\n";
}
void f2() {
cout<<"f2 from base class\n";
}
virtual void f3() {
cout<<"f3 from derived class\n";
}
};
class Derived: public Base {
public:
void f1() {
cout<<"f1 from derived class\n";
}
void f3() {
cout<<"f3 from derived class\n";
}
};
int main()
{
Derived d;
d.f1();
d.f2();
d.f3();
Base *q = new Derived();
q->f1();
q->f2();
q->f3();
return 0;
}
// Output:
// f1 from derived class
// f2 from base class
// f3 from derived class
// f1 from base class
// f2 from base class
// f3 from derived class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment