No Ordinary Love
No Ordinary Love

Reputation: 569

Implementing multiple interfaces with same method names and varying parameters in C++

I'm trying to create a class in C++ that implements multiple interfaces that have the same method names but have varying signatures.

#include <string>
#include <iostream>

using namespace std;

class IA {
public:
    virtual void method(int i) = 0; // Signature is different from IB::method

    virtual ~IA() { }
};

class IB {
public:
    virtual void method(const string& s) = 0; // Signature is different from IA::method

    virtual ~IB() { }
};

class MyClass : public IA, public IB {      
    virtual void IA::method(int i) {
        cout << "IA::method " << i << endl;
    }

    virtual void IB::method(const string& s) {
        cout << "IB::method " << s << endl;
    }

    virtual ~MyClass() { }
};

This class compiles using Visual C++ 2017. However, I would like to separate the method implementations from the class header but moving the implementation outside of the class declaration is causing compile errors.

For example, this doesn't work:

class MyClass : public IA, public IB {
    virtual void IA::method(int i);
    virtual void IB::method(const string& s);

    virtual ~MyClass() { }
};

void MyClass::IA::method(int i) {
    cout << "IA::method " << i << endl;
}

void MyClass::IB::method(const string& s) {
    cout << "IB::method " << s << endl;
}

Visual C++ 2017 reports this error:

"C2509 method: member function not declared in 'MyClass'"

Out of curiosity, I compiled the two class declarations using other compilers (g++ and clang) and they both failed to compile.

Is this some Visual C++ specific behavior?

Upvotes: 0

Views: 855

Answers (1)

Victor Padureanu
Victor Padureanu

Reputation: 614

There is no need to mark your functions as so: IA::method

The difference is done by the calling part of the signature.

class IA {
public:
    virtual void method(int i) = 0; // Signature is different from IB::method

    virtual ~IA() { }
};

class IB {
public:
    virtual void method(const string& s) = 0; // Signature is different from IA::method

    virtual ~IB() { }
};

class MyClass : public IA, public IB {
public:    
    void method(int i) override { // No need for IA::method
        cout << "IA::method " << i << endl;
    }

    void method(const string& s) override { // No need for IB::method
        cout << "IB::method " << s << endl;
    }

    virtual ~MyClass() { }
};

Upvotes: 2

Related Questions