user2814916
user2814916

Reputation: 83

What's the point of virtual functions other than allowing a function of the same name in the derived class?

Example: http://msdn.microsoft.com/en-us/library/9fkccyh4.aspx

In this example (yes I know it's just an example) all the derived classes override the Area method in the base class. Surely if in each derived class we called the method Area1 rather than Area then overriding wouldn't be necessary?

Is it purely to ensure that each derived class has access to the Area method?

Upvotes: 0

Views: 72

Answers (2)

stevepkr84
stevepkr84

Reputation: 1657

It's not about having the same name, it's about a derived class being able to override the base class functionality, to do something more specific/different when required. The derived class can choose not to override the method and in that case it will use the base class method instead.

Imagine a BaseCar class with an OpenDoor method. The BaseCar OpenDoor method would handle most use cases, e.g pulling the door outwards to open it, but for say an instance of SuperCar, you could override the OpenDoor method to handle it's own approach, e.g pulling the door upwards to open it.

Using this approach, you can be confident that with any instance of BaseCar, when you call OpenDoor, it will call the appropriate code.

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

You can't tell me that this:

shape.Area1

is nicer than:

shape.Area

Anything virtual exists because it allows you to change functionality in derived classes. Let's take that MSDN article a step further.

Say you have a list of Shape:

var list = new List<Shape>() { new Circle(), new Square(), new Triangle() };

Shape has a virtual method called GetName().

public virtual string GetName() {
    return "Shape";
}

Now let's assume we are creating a drawing application that must render the names of these shapes in a rendering loop. This is how I assume you would implement it, given your comment above:

while (true) {
    foreach (Shape s in list) {
        if (s is Circle) {
            render(((Circle)s).GetName1()); // Circle's "GetName1" method you've defined.
        }
        else if (s is Square) {
            render(((Square)s).GetName1()); // Square's "GetName1" method you've defined.
        }
        else if (...) // and so on..
    }
}

Why would you do that.. when you can do this:

public class Square : Shape {
    public override string GetName() { // Note, same name
        return "Square";
    }
}

// ... other classes overriding the method here ...

while (true) {
    foreach (Shape s in list) {
        render(s.GetName());
    }
}

Each derived class implements its own GetName method.. allowing you to call that same method on each item in the list.. but it is dispatched to each individual implementation.

Upvotes: 1

Related Questions