Click here to Skip to main content
15,889,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everybody. I am trying to implement two abstract methods (same name, same signatures). The problem is, I can define a method inside the class, but I cant (or I dont know how to) define it outside the class.
Is my syntax bad or it cannot be done this way in C++?
Could you please help me? Thank you!

What I have tried:

This is my sample code:

C++
interface IA
{
public:
	virtual void Test()=0;
};

interface IB
{
public:
	virtual void Test()=0;
};

class CTest:public IA, public IB
{
public:
	void IA::Test();
	void IB::Test();
};

void CTest::IA::Test()			// error C2509
{
}



But this one works like a charm (but I dont want internal definitions):
C++
class CTest:public IA, public IB
{
public:
	void IA::Test() {cout << "Test from A" << endl;}
	void IB::Test() {cout << "Test from B" << endl;}
};
Posted
Updated 23-Aug-22 3:27am

1 solution

What's wrong with
C++
class IA
{
public:
  virtual void Test()=0;
};

class IB
{
public:
  virtual void Test()=0;
};

class CTest:public IA, public IB
{
public:
  void Test() override;
};

void CTest::Test()
{
}
?
 
Share this answer
 
Comments
Rick York 23-Aug-22 9:52am    
Doesn't this have a diamond problem? https://www.cprogramming.com/tutorial/virtual_inheritance.html
CPallini 23-Aug-22 9:58am    
Nope. In the above code, the compiler exactly knows which is the method to call. Try:

using namespace std;
class IA
{
public:
  virtual void Test()=0;
};

class IB
{
public:
  virtual void Test()=0;
};

class CTest:public IA, public IB
{
public:
  void Test() override;
};

void CTest::Test()
{
  cout << "Test\n";
}

int main()
{
  CTest ct;

  IA * pA = &ct;
  IB * pB = &ct;

  ct.Test();
  pA->Test();
  pB->Test();

}

Greg Utas 23-Aug-22 10:47am    
Test overrides IA::Test and IB::Test simultaneously. Defining functions with the same name in base classes that will be multiply inherited seems dubious to me, but maybe there are legitimate examples.
Member 13749758 23-Aug-22 15:50pm    
Thanks for your answer. I've already tried similar way. But the problem is that in my first sample, I have two methods with same name, same signatures, distinguished by scope resolution operator, but I cant define these methods outside class CTest.
I just wonder if it is possible. I dont want one method to override two virtual methods (as in your reply). I want one method override the one from IA and second method override the one from IB.

This one works:
class CTest:public IA, public IB
{
public:
void IA::Test() {cout << "Test from A" << endl;}
void IB::Test() {cout << "Test from B" << endl;}
};

But I want it to be outside the class...

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