-1

I'm trying to determine how to name my virtual function in the derived class.

Base.h
class Base 
{
public:
    virtual void Virtual() = 0;
};

Derived.h
class Derived : public Base {
public:
    void Virtual();
};

Derived.cpp
Derived::Virtual() // or Base::Virtual
{
  cout << "Derived Virtual.\n";
}

Do I use Derived::Virtual or Base::Virtual in the implementation file and what are issues with going either way?

1 Answers1

1

It depends on what you want to achieve.

Derived::Virtual will define the overridden function, while Base::Virtual will define the base class function. Both can be done. You can't skip defining the former, that is, Derived::Virtual since it's not pure virtual, and once it gets called when you have't defined it, there's gong to be a linking error.

It does make sense to define Base::Virtual to provide some common behavior, and then call that function without using the virtual dispatch by qualifying it fully like this:

void Derived::Virtual() {
    Base::Virtual();
    std::cout << Derived::Virtual() < "\n";
}

See C++ pure virtual function have body and Does it make any sense to define "pure" virtual functions in the base class itself? for reference.

Community
  • 1
  • 1
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
  • 2
    That's quite an anti-pattern, because a programmer can easily forget the call and the compiler will not notice, resulting in strange run-time bugs. A better approach is to have a **public non-virtual** function which has the common behaviour and calls a **private pure virtual** function to be implemented in the derived class. – Christian Hackl Dec 02 '16 at 19:28
  • @ChristianHackl Right, that's the template method. I actually haven't looked at it this way, just quoted the common idiom of calling a pure virtual function by fully qualifying it. What are the real use cases of this C++ functionality? – iksemyonov Dec 02 '16 at 19:38