Morat
Morat

Reputation: 503

Why doesn't the compiler show an error with these return types?

Running a default installation of Ubuntu 11.10 with the latest version of NetBeans. I have something similar to the following:

class MyClass {
    public:
        Type1 RunAlgo();
    private:
        Type2 Run();
}

Type1 MyClass::RunAlgo() {
    //additional code
    return Run();
}

Type2 Run() {
    //additional code
    Type2 obj;
    return obj;
}

Type1 and Type2 are completely unrelated. I came upon this by making a typo in the return type when I was writing the Run() method and was amazed that it compiled. I am just wondering why this does not return an error and just compiles fine? What am I missing?

EDIT: New sample. This does generate an error as a stand alone project. Can't seem to spot why the real project would indeed compile.

class Node { };

//only difference here is that in my code I have a custom comparer
typedef map<Node*, map<Node*, double> > Network; 

class HMM {
    Network _network;
};

class Algorithm {
    public:
        HMM RunAlgo();
    private:
        Network _network;
        Network Run();
};

HMM Algorithm::RunAlgo() {
    return Run();
}

Network Algorithm::Run() {
    return _network;
}

EDIT2:

I apologize for my badly formulated question and example. I will be more careful in the future about examples. I've been working for a bit over 10 hours and lost focus. The following example reproduces my case:

#include <map>

using std::map;

class Node {

};

typedef map<Node*, map<Node*, double> > Network;

class HMM {
    public:
        HMM(const Network& network) {};
    Network _network;
};


class TestClass {
    public:
        HMM RunAlgo(int x, int y);
    private:
        Network _network;
        Network Run();
};

HMM TestClass::RunAlgo(int x, int y) {
    return Run();
}

Network TestClass::Run() {
    return _network;
}  

After adding that specific constructor to the HMM class it compiles without problems. I didn't know this could be done as this is the first time I encounter this case. Again I apologize if I wasted your time and I appreciate you trying to help me.

Upvotes: 0

Views: 101

Answers (2)

You didn't show your actual code; the example you gave us don't compile (GCC 4.6 on Debian/Sid/AMD64)

% g++ -Wall exmorat.cc 
exmorat.cc:3:9: error: 'Type1' does not name a type
exmorat.cc:5:9: error: 'Type2' does not name a type
exmorat.cc:8:7: error: expected initializer before 'MyClass'

But what you describes may happen when you have conversions or casting involved. You should show your actual code (or a simplified code which exhibits the symptoms) to get real help.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

After fixing the mistakes in your non-testcase, my compiler does error out.

Your statement that Type1 and Type2 are unrelated must be false.

Take care on a real testcase next time.

Upvotes: 1

Related Questions