-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Virtual Function #14
Comments
|
#include <iostream>
class Animal {
public:
virtual void eat()
{
std::cout << "I eat like a generic Animal.\n";
}
};
class Wolf : public Animal {
public:
void eat() { std::cout << "I eat like a wolf!\n"; }
};
class Fish : public Animal {
public:
void eat() { std::cout << "I eat like a fish!\n"; }
};
class OtherAnimal : public Animal {
};
int main()
{
Animal *anAnimal[4];
// dynamic binding
anAnimal[0] = new Animal();
anAnimal[1] = new Wolf();
anAnimal[2] = new Fish();
anAnimal[3] = new OtherAnimal();
for(int i = 0; i < 4; i++) anAnimal[i]->eat();
return 0;
}
-> Dynamic Binding works |
#include <iostream>
using namespace std;
class B
{
public:
virtual int get_val() { return 0; };
};
class D1 : public B
{
public:
D1(int x_val) : x(x_val){};
virtual int get_val() { return x; };
private:
int x;
};
class D2 : public B
{
public:
D2(int y_val) : y(y_val){};
virtual int get_val() { return y * y; };
private:
int y;
};
int main()
{
const int MAX = 5;
D1 Zero(0), One(1), Two(2);
D2 Three(3), Four(4);
B *B_Array[MAX];
B_Array[0] = &Zero;
B_Array[1] = &One;
B_Array[2] = &Two;
B_Array[3] = &Three;
B_Array[4] = &Four;
for (int i = 0; i < MAX; ++i)
{
cout << i << ": " << B_Array[i]->get_val() << endl;
}
return 0;
}
-> Dynamic Binding works |
Pure Virtual Function
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: