What is the most concise yet accurate way to descr

2019-06-20 08:27发布

Being asked to describe what a virtual function is seems to be one of the most common questions in interviews assessing basic C++ knowledge. However, after several years programming C++, I still have the uncomfortable feeling that I don't really understand how best to define what they are.

If I consult wikipedia, I see the definition of virtual function is:

"In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature"

This definition seems simple and elegant, and not C++ specific. But to me it doesn't seem to capture the concept of a virtual function in C++, since surely a non-virtual function can also be overridden within an inheriting class by a function with the same signature.

If I'm asked to describe what a virtual function is informally, I say something about pointers like "it's a method such that when you call it via a base class pointer, the version of it defined in the derived class is called instead, if the pointer actually points to an instance of a derived class". This doesn't seem like a very elegant description of the concept. I know that people say this is how "polymorphism" is achieved in C++ (polymorphism, as far as I understand, roughly being the whole idea of organizing objects into hierarchies), but I don't know of a fancier way to understand or explain the mechanism than to go through the example with the pointers.

I guess I'm confused about whether the "pointer" description of virtual functions is something fundamental to their definition, or just something incidental to their implementation in C++.

11条回答
SAY GOODBYE
2楼-- · 2019-06-20 08:41

I've always thought that this quote captures the essence of virtual functions:

A virtual function is a way of defining a family of related behaviors that can be customized by the entities that actual have to do those behaviors.

If you ignore all the C++-isms of virtual functions - how having virtual functions enables dynamic_cast to work for objects of the class type, how they're only treated virtually if accessed through a pointer, how virtual destructors are completely different from virtual non-destructors, etc. - I think that the above statement gets at the heart of what virtual functions are all about.

The main reason I like this statement is that it describes virtual functions in a way that decouples them from programming. You could explain virtual functions to a non-technical person using this definition by giving some concrete analogies. For example, the idea of "turning on a light" could be thought of as a virtual function because the actual mechanics of what happens when you turn on a light depends entirely on the particular light you're using (incandescent? fluorescent? LED?), but the conceptual idea is the same in each case. Of course, it's not a perfect analogy, but I think it gets the point across well enough.

More generally, IMHO, if you're ever asked to describe something informally, try as much as possible to distance yourself from the particular programming language you're using and, if at all possible, from computers at all. Try to think of the most general setting in which the concept applies, and then describe it at that level. Then again, I teach introductory CS courses, and so I have a bit of a bias toward this domain, so I have no idea how applicable this is in a job interview setting. :-)

查看更多
太酷不给撩
3楼-- · 2019-06-20 08:41

since surely a non-virtual function can also be overridden within an inheriting class by a function with the same signature.

No thats incorrect. The function only gets redefined not overriddden in that case.

查看更多
闹够了就滚
4楼-- · 2019-06-20 08:42

The difference lies in how the compiler decides which implementation to "bind" to the method call when it compiles the source code. For a virtual fumction, the implementation chosen is based on the actual concrete type of the object itself, not on the type of the variable. This means that when you cast an object to a base class or interface, the implementaion which will get executed is still the implementation defined on the derived class that the object actually is.

In puesdo code

// for a virtual function
public class Animal { public virtual void Move() { Print "An animal Moved." } }
public class Dog: Animal  { public void Move() { Print "A Dog Moved." } }

Animal x = new Dog();
x.Move()  // this will print "A Dog Moved."

For a non-virtual function, the implementation chosen will be based on the type of the variable, which means that when you cast an object to a base class, (i.e., change the type of the variable ) the method implementation defined in the base class will be chosen by the compiler and it will get executed, not the implementation in the derived class...

// for a non-virtual function
public class Animal { public void Move() { Print "An animal Moved." } }
public class Dog: Animal  { public void Move() { Print "A Dog Moved." } }

Animal x = new Dog();
x.Move() // this will print "An animal Moved."
查看更多
迷人小祖宗
5楼-- · 2019-06-20 08:43

Your informal definition is a good summary of what a virtual pointer does. It sounds like you're looking to also describe how it works, but since the C++ standard doesn't specify, any "how" description would be specific to a particular implementation and not the C++ language in general.

The C++ standard is all about behavior and says almost nothing about implementation. There's even the "as-if" rule, which allows any alternate implementation that provides the same visible behavior.

查看更多
老娘就宠你
6楼-- · 2019-06-20 08:45

If an interview is about your knowledge in C++ I think there is not a sin to refer to a pointer.

You can say simply that "virtual functions is a mechanism to allow an object to express it's class behavior, even if it's accessed through a base class pointer".

More than this (if you think about "pure virtual functions") it's also a mechanism to force a whole hierarchy of classes to provide a specific method, without defining a default method implementation in the base class.

查看更多
迷人小祖宗
7楼-- · 2019-06-20 08:50

"I guess I'm confused about whether the "pointer" description of virtual functions is something fundamental to their definition, or just something incidental to their implementation in C++."

It is not incidental. The concept of virtual functions works only for pointers or references.


Virtual functions are needed when the derived class method bearing the same signature that of base class is overridden to different functionality.

class Polygon
{
    public:
    virtual float area()
    {
        std::cout << "\n No formula in general \n" ;
    }
    virtual ~Polygon();
};

class Square
{
    public:
    float area()
    {
        std::cout << "\n Side*Side \n" ; 
    }
    ~Square();
}

Polygon* obj = new Square ;
obj -> area() ;  // Ok, Square::area() is called. 

Square obj1;
Polygon& temp = obj1 ; // Ok, Square::area() is called

Square obj2;
Polygon temp1 = obj2 ; // Polygon::area() is called because of object slicing.
查看更多
登录 后发表回答