Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function issue

I am using native C++ with VSTS 2008. A quick question about virtual function. In my sample below, any differences if I declare Foo as "virtual void Foo()" or "void Foo()" in class Derived? Any impact to any future classes which will derive from class Derived?

class Base
{
public:

    Base()
    {
    }

    virtual void Foo()
    {
        cout << "In base" << endl;
    }
};

class Derived : public Base
{
public:

    Derived()
    {

    }

    void Foo()
    {
        cout << "In derived " << endl;
    }
};
like image 594
George2 Avatar asked Dec 12 '22 23:12

George2


2 Answers

No difference. But for the sake of readbility I always keep the virtual whenever it is.

like image 102
Jay Zhu Avatar answered Dec 15 '22 12:12

Jay Zhu


No, as long as it has the same signature as the member function in the base class, it will automatically be made virtual. You should make it explicitly virtual, however, to avoid confusing anyone reading the code.

like image 34
Ferruccio Avatar answered Dec 15 '22 13:12

Ferruccio