Why do you use the virtual method?

Asked 2 years ago, Updated 2 years ago, 129 views

I started learning C++ Isn't the virtual method used by the child class to override the parent class's method? You can just override it. Why do you have to use the virtual keyword?

c++ virtual virtual-functions

2022-09-22 22:35

1 Answers

I'll explain it with an example

class Animal
{
public:
    void eat() { std::cout << "I'm eating generic food."; }
};

class Cat : public Animal
{
public:
    void eat() { std::cout << "I'm eating a rat."; }
};

int main(){
    Animal *animal = new Animal;
    Cat *cat = new Cat;
    animal->eat(); // outputs: "I'm eating generic food."
    cat->eat();    // outputs: "I'm eating a rat."
}
I'm eating generic food.
I'm eating a rat.

In the encode Add void func(Animal *xyz) {xyz->eat();} If you made the same code as the following,

class Animal
{
public:
    void eat() { std::cout << "I'm eating generic food."; }
};

class Cat : public Animal
{
public:
    void eat() { std::cout << "I'm eating a rat."; }
};
void func(Animal *xyz) { xyz->eat(); }

int main(){
    Animal *animal = new Animal;
    Cat *cat = new Cat;
    func(animal); // outputs: "I'm eating generic food."
    func(cat);    // outputs: "I'm eating generic food."
}
I'm eating generic food.
I'm eating generic food.

I paged func(cat) Not "I'm meeting a rat." "I'm eating generic food." What if we add more animals here? Should we overload func() for each animal?

The virtual method is used in this situation.

class Animal
{
public:
    virtual void eat() { std::cout << "I'm eating generic food."; }
};
class Cat : public Animal
{
public:
    void eat() { std::cout << "I'm eating a rat."; }
};
void func(Animal *xyz) { xyz->eat(); }

int main(){
    Animal *animal = new Animal;
    Cat *cat = new Cat;
    func(animal); // outputs: "I'm eating generic food."
    func(cat);    // outputs: "I'm eating a rat."
}
I'm eating generic food.
I'm eating a rat.


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.