Jan
Jan

Reputation: 83

Virtual function not inherited from interface

I have an interface class with a default implementation and an inheriting class with its header and cpp file.

List.h

class List {
public:
    virtual int search(const string searchCharacters, bool caseSensitive){return 0;}
}

MyList.h

class MyList : public List {

}

MyList.cpp

int MyList::search(const string searchCharacters, bool caseSensitive)
{
    // Implementation code
}

Now, I'm getting member function not declared in 'MyList' for some reason. I have a Java background and still have some issues adjusting to C++ way of things. Why isn't the definition being carried through the MyList header file?

Upvotes: 1

Views: 711

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Unlike Java non-private member methods which are always virtual, a C++ member-function is not virtual unless you have explicitly declared it virtual in the base class:

class List {
public:
    virtual int search(const string searchCharacters, bool caseSensitive) {
        return 0;
    }
};

If you want to supply an implementation of an override in your cpp file, you need to also supply a declaration of the member-function that you are overriding in your header:

class MyList : public List {
public:
    int search(const string searchCharacters, bool caseSensitive) override;
};

Note the optional override specifier at the end of the declaration.

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172894

You need to declare the function in the derived class:

class MyList : public List
{
public:
    int search(const string searchCharacters, bool caseSensitive);
}

Note that the declaration and defination are not the same thing in C++. In this case, you can't define the member function in cpp file without declaration. If you don't declare (and define) it, then derived class will inherit it from the base class, including the defination.

And if you want it to be polymorphic you need to make it virtual in the base class, and it's better to make the destructor virtual at the same time if you'll use them by base class's pointer:

class List
{
public:
    virtual int search(const string searchCharacters, bool caseSensitive){return 0;}
    virtual ~List() {}
}

As @SergeyA pointed, you can also make it a pure virtual function to make it be similar with java-style interface more. In this case you don't need to provide defination for it. (You still could provide one)

class List
{
public:
    virtual int search(const string searchCharacters, bool caseSensitive) = 0;
    virtual ~List() {}
}

At last, C++ and Java are totally different. If you want to master C++, try to think in C++ style.

Upvotes: 4

Related Questions