EDIT: Oh, well, it looks like I was beaten to the punch by Adek. This is what comes of taking too long to write these damn things out.
This is what I was saying before about having to have the class definitions visible to the referencing code. You generally want to have class definitions in header files which the referring code can then [tt]#include[/tt].
In the case given above, all of the method functions are inline, so there is nothing to separately compile. If you want to have the function implementations separate from the class definitions, you need to have a separate source file for those.
Here is a version of the code you wrote, broken down in the manner described:
Code: Select all
// a.h - class definition for class a
// add a header guard to prevent duplicate includes
#ifndef __A_H__
#define __A_H__
class a {
protected:
public:
a();
void meth1();
};
#endif
Code: Select all
// a.cpp - method implementations for class a
#include "a.h"
#include <iostream>
using namespace std;
a::a(){
cout << "In a constructor" << endl;
}
void a::meth1() {
cout << "Class a Method 1" << endl;
}
Code: Select all
// main() program, with local definition of class b
#include <iostream>
#include "a.h"
using namespace std;
class b: public a
{
public:
b():a()
{
cout << "In b constructor" << endl;
}
void meth1()
{
a::meth1();
cout << "Class b Method 1" << endl;
}
};
int main()
{
b b1;
b1.meth1();
cout << "anselm" << endl;
}
Note that the header declarations for IOSTREAM have been changed in the newer C++ standard, and that you need to have a [tt]using namespace[/tt] statement to make the I/O stream classes visible, as well. Also, while variable names can be scope-overridden, class names cannot be; declaring a variable 'a' after declaring a class 'a' causes a type-resolution conflict.
Finally, you will need to link the object files together before you can produce an executable; how you would do this will depend on your development kit. Most IDEs support some form of project or make file, which will allow you to link the files automagically after compilation. For a command line compiler, you can either compile the separate file then link them manually, or you can use a make utility like the standard GNU make (the gcc compiler-driver allows you to link at compile time, but any non-trivial compile would need too long an options list for this to be feasible). A simple make file for this (assuming Linux) might be something like this:
Code: Select all
# makefile for b
b: a.o b.o
???gcc a.o b.o -o b
a.o: a.cpp a.h
???gcc -c a.cpp -o a.o
b.o: b.cpp a.h
???gcc -c b.cpp -o b.o
Note that this has not been tested; you would probably have to add the appropriate flags and so forth to make it work correctly.