C++ virtual functions

Discussion in 'OT Technology' started by Pip, Mar 18, 2004.

  1. Pip

    Pip Guest

    I have an interview tomorrow morning for an entry-level Java/C++ position and am brushing up on my C++ since I'm much more familiar with Java.

    I've been researching virtual functions and think I finally have a grasp on what they are. So basically you need to declare a function virtual in the base class so that if you have a pointer to base class it can dynamically call the derived class's function?

    class Base {
    virtual void draw();

    class Derived : public Base {
    void draw();

    int main() {
    Derived d;
    Base * bp = &d;
    bp.draw(); // this will actually call Derived's draw()

    So it seems that virtual functions provide the same functionality as overloaded methods in derived classes in Java.

    Is this correct? If not, please help!
  2. WERUreo

    WERUreo Imua!

    Oct 15, 2003
    Likes Received:
    Daytona Beach, Florida
    I'm not the greatest at C++, Java, or object-oriented methodologies, but isn't overloading when you have more than one function with the same name but with different sets of parameters and/or return types? Whereas, overriding a function is when a derived class has a function with the same name and same set of parameters, but with a different implementation...

    So, if there is method overriding in Java, that would most likely be the comparison. It's been a while since I've programmed in Java, and I just started a software engineering job where we use C++, but I came from a background of non-OO languages, so I'm still learning.
  3. StevesVR4

    StevesVR4 Get Arrested

    Jul 1, 2003
    Likes Received:
    In Java, every function is virtual. For polymorphism to work, the functions must be virtual. Overloading functions is when you have some functions with the same name but different parameter lists. That is independant of virtual functions. Virtual functions are necessary when a derived class overrides a function in a base class. If the function is not virtual, the derived class will not have its function call if you are using a pointer of the base class type.

Share This Page