1

when a have the same function name in a base class and a derived class with a different code for each function is it necessary to set my function as virtual or is it just part of better programming?

Dchris
  • 2,867
  • 10
  • 42
  • 73

5 Answers5

3

It's not necessary at all to make the method virtual. However, it should be virtual if you want it to be called through "late binding", i.e. if, given a base pointer, you want the derived method to be called.

If you don't want that to happen, it's often because these methods are unrelated, in which case you better give the method in the derived class a different name.

Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
0

Calls of virtual functions are dispatched dynamically at run-time. This is the basis of polymorphism.

A function that is declared as virtual in the base-class, will implicitly be virtual in sub-classes.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
0

No it's not necessary to do that.

In fact, when to declare virtual and when not to is part of effective program design itself.

Look here for more information on Virtual and Pure Virtual functions.

Community
  • 1
  • 1
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0

If you expect to use base class pointers to derived class instances, and the functions have the same signature, then you will probably want to make the function virtual, as well as make the class destructors virtual. This way, if someone has a parent-class pointer to a derived type and they want to call that function, they will probably want to execute the child class' version if it's different from the parent's.

class Parent
{
public:
    virtual ~Parent() {}

    virtual void doSomething()
    {
        std::cout << "Parent";
    }
};

class Child : public Parent
{
public:
    virtual ~Child() {}

    virtual void doSomething()
    {
        std::cout << "Child";
    }
};

int main()
{
    Parent *p = new Child();
    p->doSomething(); // prints "Child" because of dynamic dispatch
}
wkl
  • 77,184
  • 16
  • 165
  • 176
0
class A {
public:
    void Foo() {}
    virtual void Bar() {}
};
class B : public A {
public:
    void Foo() {}
    virtual void Bar() {}
};

int main() {
    A *a = new A;
    B *b = new B;
    A *c = b;

    a->Foo();  // calls A::Foo on a
    b->Foo();  // calls B::Foo on b
    c->Foo();  // calls A::Foo on b

    a->Bar();  // calls A::Foo on a
    b->bar();  // calls B::Foo on b
    c->bar();  // calls B::Foo on b

    delete a;
    delete b;
}

See C++ FAQ § Inheritance — virtual functions.

ephemient
  • 198,619
  • 38
  • 280
  • 391