Created
February 11, 2020 13:37
-
-
Save shubham7298/26a679912f0431f4b0ebcd885115371a to your computer and use it in GitHub Desktop.
Virtual functions in C++
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 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