Hello all,
I encountered a problem on "local class name conflict",
I searched on net and found that years ago, some people also encoutered this 
kind of problem.

https://stackoverflow.com/questions/10671956/same-class-name-in-different-c-files
http://www.cplusplus.com/forum/general/32010/


Please see the following code, (BTW, it seems that the maillist can not attach 
files)

When I ran the code(Ubuntu 64bis, gcc vesion:5.4.0, the amazing result is :
localClassXInData.cpp in Data.cpp
 localClassXInData.cpp in Data.cpp


I think there is an error in Link phrase:
1. if comment out the LocalClassX definition in main.cpp, the compile will not 
compile the code --- this is as expected.
2. however, if run the code(not comment out any code), the code actually ran is 
in the Data.cpp, that is not consistent with compile phase.


Thanks!


code
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  main.cpp

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <stdio.h>
#include <stdlib.h>

#include <string>
using namespace std;

class LocalClassX
{
public:
    string name;

    LocalClassX() {
        name = "localClassXInMain.cpp" ;
    }

    virtual ~LocalClassX() {
    }

    virtual void f() {
        printf("%s in main.cpp \n ", name.c_str());
    }
};

#include "Data.h"
Data data;

int main(int argc, char* argv[])
{
    try {
        LocalClassX x;
        x.f();
        data.add(1);
    }
    catch (...) {
        printf("error \n");
        return 1;
    }
    return 0;
}


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Data.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ifndef DataH
#define DataH

#include <vector>
#include <string>
using namespace std;


class Data {
protected:
    vector<int> data;
public:
    Data();
    virtual ~Data();

    void add(int i);
};

#endif


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Data.cpp

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include <stdio.h>

#include "Data.h"

Data::Data()
{
}
Data::~Data()
{
}

class LocalClassX
{
public:
    string name;

    LocalClassX() {
        name = "localClassXInData.cpp" ;
    }

    virtual ~LocalClassX() {
    }

    virtual void f() {
        printf("%s in Data.cpp \n ", name.c_str());
    }
};

void Data::add(int i)
{
    LocalClassX x;
    x.f();

    data.push_back(i);
}

Reply via email to