Click here to Skip to main content
15,905,913 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I can override virtual function with the same name like this:
C++
class I
{
public:
    virtual void foo() = 0;
};

class J
{
public:
    virtual void foo() = 0;
};

class C : public I, public J
{
public:
    virtual void I::foo() { cout << "I" << endl; }
    virtual void J::foo() { cout << "J" << endl; }
};

But when I move the two function out of the class,like this:
C++
class C : public I, public J
{
public:
    virtual void I::foo();
    virtual void J::foo();
};
void C::I::foo() { cout << "I" << endl; }
void C::J::foo() { cout << "J" << endl; }

I got two error say 'foo' not declared in 'C'.
Is there a way to implement the two functions out of the class?
Posted

1 solution

No, you can't do it directly. There are ways around this limitation however. You would have to introduce an intermediate step:

//DECLARATION
class C : public I, public J
{
public:
    virtual void I::foo() { fooI(); }
    virtual void J::foo() { fooJ(); }

    void fooI();
    void fooJ();
};

//IMPLEMENTATION
void C::fooI() { cout << "I" << endl; }
void C::fooJ() { cout << "J" << endl; }


It isn't exactly pretty, but AFAIK it's the best way to do what you need.
 
Share this answer
 
Comments
Dnkuni 6-Mar-12 2:43am    
Pretty enough, thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900