Multiple inherience with same function name

Dear All,
I have a child class implementing two interfaces. Each interface contains a common function name. A sample code is as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class IClass1
{
public:
  virtual int add(int, int)=0;
};

class IClass2
{
public:
  virtual int add(int, int)=0;
};

/* implementation method 1 for CChild, works */
class CChild
{
public:
  int IClass1::add(int x, int y){return (x + y);}
  int IClass2::add(int x, int y){return (x + y + 100);}
};
/* implementation method 1 for CChild END, works */

/* implementation method 2 for CChild, not work */
class CChild
{
public:
  int IClass1::add(int x, int y);
  int IClass2::add(int x, int y);
};

int CChild::IClass1::add(int x, int y)  // this will not work, why? What should 
                                        // I write to separate declaration and       
                                        // definition? 
{
  return (x+y);
}

/* implementation method 2 for CChild END, not work */


I hope the example is self-explanatory.

Thanks,
Hailiang
What compiler even allows you to successfully compile implementation 1? That defeats the purpose of virtual methods.

Why not just do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

class IClass1 {
public:
    int add(int x, int y) {
        return x + y;
    }   
};

class IClass2 {
public:
    int add(int x, int y) {
        return x + y + 100;
    }   
};

class CChild : public IClass1, public IClass2 {
};

int main(int argc, char* argv[]) {
    int first, second;
    CChild cc; 

    first = cc.IClass1::add(5, 5); 
    second = cc.IClass2::add(5, 5); 

    std::cout << "IClass1::add - " << first <<
        "\nIClass2::add - " << second << "\n";

    return 0;
}
Thanks for the replay. I was using MS VC++ to compile the 1st implementation. One mistake in class CChild, it should be declared as class CChild : public IClass1, public IClass2

In implementation 1, it works with the following test code:

1
2
3
4
5
6
CChild *c = new CChild();
IClass1 *i1 = c;
cout << i1->add(1,2) << endl;

IClass2 *i2 = c;
cout << i2->add(1,2) << endl;


The reason I want to use this kind of interface is: I prefer to define pure virtual function and its related variables within one interface, and implement the virtual function within the inherent class. It is fine if the function names are all different within every interface. But, sometimes, two interfaces will have common names, as in this example.
Your first implementation does not compile with gcc. If you figure out how to accomplish this (regardless of compiler) please share it here. Good luck
Topic archived. No new replies allowed.