EEstud
EEstud

Reputation: 309

Reference to object ambigous?

This is my program and it fails because of this error : reference to 'exception' is ambiguous.

Why is that?

Is it because my class name is "exception" and C++ already has other function using the name "exeption"? For instance, in C++ we cannot use "int" as a variable. Does this logic applies here aswell? Thank you.

#include <iostream>
#include <math.h>

using namespace std;

class exception{

public:
    exception(double x,double y ,double z)
    {
    cout<<"Please input a";

    cin>>x;
    cout<<"Please input b";

    cin>>y;
    cout<<"Please input c";

    cin>>z;

    a=x;
    b=y;
    c=z;
    /*
    try{
        int sonsAge = 30;
        int momsAge = 34;
        if ( sonsAge > momsAge){
            throw 99;
        }
    }
    catch(int x)
    {
        cout<<”son cannot be older than mom, Error number :”<<x;
    }
    */
    try {
        if (a==0) {
            throw 0;
        }
        if ((b*b)-(4*a*c)<0) {
            throw 1;
        }
        cout<<"x1 is"<<(-b+sqrt(b*b-4*a*c))/(2*a)<<endl
            <<"x2 is"<<(-b-sqrt(b*b-4*a*c))/(2*a);
    } catch (int x) {
        if (x==0) {
            cout<<"Error ! cannot divide by 0";
        }
        if (x==1) {
            cout<<"The square root cannot be a negative number";
        }
    }
    };

private:
    double a,b,c;
};

int main()
{
    exception ob1(3.2,12.3,412);
    return 0;
}

Upvotes: 1

Views: 3247

Answers (2)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

Through the statement using namespace std the std::exception class is resolved as exception. Now you define a class with the same name. The compiler can now not distinguish between these two classes by the name exception. Therefore the name exception is ambigous. Defining a reference std::exception& should work though as your telling the compiler exactly which class to use.

Upvotes: 1

ecatmur
ecatmur

Reputation: 157414

std::exception is a standard class name; it is the base type of the standard exception hierarchy. You can name your own class by qualifying it as ::exception. This is an excellent reason not to use using namespace std.

Upvotes: 5

Related Questions