2 minute read

Introduction

This is a common error that occurs when we call functions that are defined in multiple files, while remaining in the same namespace.

error: “HumanPerson::talk” is ambiguous

This error is pretty straight-forward to fix as we will see below.

Fix #1: Change function definition

Essentially, when we have two functions with the same parameters and in the same namespace, we can only call one of them. If two or more exist, the compiler will give us the ambiguous error.

An easy way to fix this is to change the function definition, such as the name or the parameters.

Therefore, you must change the function definition which is causing the ambiguous error. Here is an example: Main.cpp


#include <iostream>
#include <string>
#include "HumanPerson.h"


int main()
{
  HumanPerson a;
  a.talk();
  return 0;
}

HumanPerson.h

#pragma once
#include "Person.h"
#include "Human.h"
class HumanPerson : public Human, public Person //Note we are using multi-level inheritance here. This means that we are inheriting from both Human and Person.
{
private:
	int m_data;
};

Human.h

#pragma once
class Human {
public:
	void talk() { std::cout << "Human!" << std::endl; } //same function as below
};

Person.h

#pragma once
class Person {
public:
	void talk() { std::cout << "Person!" << std::endl; } //Same function as above
};

Note here that we’re calling the talk function which is defined in both Person and Human. Therefore, the compiler does not know which one is the correct one to call. If we change the name of the talk function in Human.h to talkHuman, then the error will be fixed because the compiler will know which one to call.

FIX: Human.h

#pragma once
class Human {
public:
	void talkHuman() { std::cout << "Human!" << std::endl; } //same function as below
};

The compiler should now be able to tell apart both functions when we call them, thus fixing the error.