views:

155

answers:

1

I'm working on a class assignment that started small, so I had it all in one file. Now it's gotten bigger and I'm trying to separately compile main, functions, and classes (so all the classes are together in one .h and one .cpp) I have one class B, which is the parent of a lot of others and comes first in the file. One of its data members isn't working now that I'm using separate compilation, which is causing dozens of errors.

In .h

class A;
class B {
public: 
    B (){}
    A* myptr;
    void whatever();
    vector<A*> myAs; //this one is the problem
};

In .cpp

void B::whatever() {
    vector<A*> newvector; //no problem!
    myptr = &something; //no problem!
    for (vector<A*>::iterator iter = myAs.begin(); iter != myAs.end(); ++iter) {
     //error!
    }
}

I get errors: either "myAs was not declared in this scope" or "class B has no member myAs."

I've included < vector >, forward-declared class A as you see above, and I definitely remembered to include the .h at the top of the .cpp! Is there something about vectors or classes and separate compilation that I don't understand? This is in Xcode, BTW.

+4  A: 

It's not just vector. It's std::vector because it is within the namespace called std. That's why the compiler moans. It doesn't know what vector<A*> means. Say std::vector<A*> instead.

Do not add using namespace std; now into the header because of this. It may be OK for the assignment to put it into the .cpp file to save typing if you wish. But it's a really bad idea to put such a line into a header: Because you don't know which files will need your header in future. The situation can quickly get out of hand as the amount of files including your header grows with time. The header should therefor include only the names and headers that it really needs so that it causes as little name conflicts as possible - whereas that using namespace std; line would make all names of std visible directly.

Johannes Schaub - litb
You've identified one of my pet hates (programmers who put using declaration in header files). +1.
Andrew Shepherd
Thank you! I can't believe I didn't think of that, because I *did* realize I had to change string to std::string. I had no idea that vector was subject to the same.
eom