James
James

Reputation: 190

C++: Type casting operator overloading - Visual studio 2013 internal error

I was overloading type casting operators, and internal error has occurred in Visual Studio 2013.

This is the header of the exponent class:

#pragma once
#include "Calc.h"
#include <iostream>

using namespace std;


class Exponent
{

private:
    int base;
    int exponent;
public:
    Exponent();
    Exponent(int a)
    {
        base = a;
    }

    int getBase()
    {
        return base;
    }


};

void printExp(Exponent e)
{
    cout << e.getBase() << endl;
}

and this is calc.h I wrote that will contain overloaded type casting function:

#pragma once
#include "Exponent.h"

class Calc
{
private:
    int acc;
public:
    Calc();
    Calc(int a);

    operator Exponent()  //this is where I get an error. 
    { 
        return Exponent(acc); 
    }


};

And here's the main function:

#include "stdafx.h"
#include <iostream>
#include "Exponent.h"
#include "Calc.h" 

using namespace std;

int main()
{
    Calc c(6);

    printExp(c);
    return 0;
}

I have no idea why I get an error here:

operator Exponent()  //this is where I get an error. 
{ 
    return Exponent(acc); 
}

This is somehow making Visual Studio crash, showing an error like this:

Microsoft(R) C\C++ Optimizing compiler has stopped working...

Upvotes: 1

Views: 433

Answers (2)

user2723403
user2723403

Reputation: 1

This code no longer crashes in Visual Studio "14" CTP.

It won't compile because you included Calc.h in Exponent.h, which means the compiler sees class Calc before it sees class Exponent, so you're trying to define a conversion operator to a type that the compiler doesn't know exists yet.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400284

An internal compiler error (ICE) is a compiler bug—a well-functioning compiler should always report sensible errors for erroneous code. I'd suggest you file a bug report on connect.microsoft.com.

However, you do have a clear problem with your code: you have a circular dependency between your two header files. Exponent.h includes Calc.h, which in turn includes Exponent.h. Even if the compiler weren't crashing with an ICE, it would still report an error (likely of the "undefined symbol" variety) with this code.

There's a simple fix to this case—because Exponent.h doesn't actually have any dependencies on Calc.h, you can just remove the #include "Calc.h" line from Exponent.h, and the circular dependency will be gone.

Upvotes: 5

Related Questions