Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can some one explain how below program becomes infinte loop of "AabAabAab.."

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

using namespace std;

class Base {
public:
    Base(int j=1):i(j)
    {cout<<"B";}
private:
    int i;
};

class Case{
public:
    Case(int j=1):i(j) {cout<<"A";}
    operator Base() { cout<<"ab"; return *(new Case); }
private:
    int i;
};

int main()
{
    Base obj = Case();
    return 0;
}
share|improve this question
    
it runs fine on vc++ editor..just compiled. –  PowerPC Jun 11 '13 at 19:03
    
wow. that would make a nice interview question –  AlexK Jun 11 '13 at 19:29

2 Answers 2

up vote 7 down vote accepted
Base obj = Case();

This calls the Case default constructor, printing A. Then, there is a conversion to Base via this operator, which has an infinite recursion:

operator Base() { cout<<"ab"; return *(new Case); }

Because it attempts to return a Case instance (prints abA), which must be converted to Base, which invokes the conversion operator, which creates a Case instance (prints abA), which must be converter to Base, which...

share|improve this answer

Can some one explain how below program becomes infinte loop of "AabAabAab.."

Not really infinite. This will eventually crash your program because of stack overflow. This is what's going on. Here:

Base obj = Case();

You are creating a temporary object of type Case and using it to initialize an object of type Base.

The only way this can be done is by picking the user-defined conversion operator of Case, which can return a Base.

Now this conversion operator in turn happens to create a temporary object of type Case, from which the return value of the operator should be initialized.:

return *(new Case);

Since the return value is itself of type Base, the temporary now has to be converted to an object of type Base - and since the temporary has type Case, the same user-defined conversion operator is invoked again.

This is what attempts to generate an infinite recursion. Since each function call requires creating a stack frame, however, your neverending recursion will eventually cause a stack overflow, and your process will be terminated.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.