0
class Base
{
    virtual void foo();
}


class Derived : public Base
{
    void foo();
}

It it OK? Or it can make some problems? I think it insist "DO NOT INHERIT FROM DERIVED".

sth
  • 222,467
  • 53
  • 283
  • 367
Gimun Eom
  • 411
  • 5
  • 17
  • 1
    Please tag your question with the language you're talking about (C++ I guess). – Mat Dec 15 '13 at 06:48
  • Yes please tag as in C# it will give you following warning. "hides inherited member Base.foo(). To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." You can read about it [here](http://msdn.microsoft.com/en-us/library/aa691135(v=vs.71).aspx) – Adarsh Shah Dec 15 '13 at 06:59
  • It's not even possible. The function remains virtual, even if you don't say so. – user207421 Dec 15 '13 at 07:19

3 Answers3

2

Once you marked the foo() function in Base class as virtual it is implicitly virtual in Derived class, even if you don't mention the keyword virtual in front of it.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

virtualness is inherited. Even if you do not declare an overridden method virtual, it will be virtual.

Hence, if you access an object of Derived using Base pointer or reference, it will call foo of Derived.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
0

virtual functions are inherited automatically. So even if you don't declare it as virtual, it is virtual actually.

The reason for you to explicitly declare it as virtual is for better clarification so that anyone reading this code can instantly understand that it is a virtual functions, without having to check the base class declarations.

richard.g
  • 3,585
  • 4
  • 16
  • 26
  • Marking it virtual guarantees that it's virtual, even if the base class has a member function with the same signature that is **not** virtual. There's no shortcut that lets you write correct code without understanding what you're doing. (Okay, the new `override` keyword might make life easier for lazy programmers...) – Pete Becker Dec 15 '13 at 14:12