I am trying to write a series of programs that use the same main (main.cpp) file, but with different secondary source files (object1.cpp, object2.cpp, etc). So I will be compiling them essentially like this:
g++ -o program1.exe main.cpp object1.cpp
g++ -o program2.exe main.cpp object2.cpp
What I want to do is have objectN.cpp define a class with certain methods implemented, which will be called from the main file. The source codes look something like this:
header file (object.hpp)
#ifndef INCLUDE_OBJECT_HPP
#define INCLUDE_OBJECT_HPP
class MyObjectInterface
{
public:
MyObjectInterface();
virtual ~MyObjectInterface() {};
virtual void MethodA() = 0;
virtual void MethodB() = 0;
};
#endif
object1.cpp
#include <iostream>
#include "object.hpp"
using namespace std;
class MyObject : public MyObjectInterface
{
private:
int member;
public:
MyObject(int a) { member = a; }
void MethodA() { cout << member << endl; }
void MethodB() { cout << member*2 << endl; }
};
main.cpp
#include <iostream>
#include "object.hpp"
using namespace std;
MyObjectInterface *x;
int main()
{
x = new MyObject(1);
x->MethodA();
x->MethodB();
return 0;
}
object2.cpp would have a similar structre to object1.cpp but the class would have different data members.
I can’t get this to work, because I need to include the the class declaration of MyObject in main.cpp. But each object*.cpp file will declare the MyObject class with different members, so I cannot just simply make a seperate object.hpp header and include it in main, because I need different headers for different objects. The only thing main should have to know about is the methods.
I hope I’ve explained the problem clearly; if not leave a comment and I’ll try to clarify. It seems like there should be a really simple way of doing something like this but I can’t figure it out.
Thanks
NO you don’t. Make a factory method
*.h:
*.cpp:
However, having identically named classes with identical structure declared in different files might confuse some compilers in certain circumstances (rare thing, but it can happen).
Also, better solution would be to rethink your program structure. Because your derived classes are supposed to have different data members, it means you’ll probably need to access those data members. Because you’ll probably need to access those memebrs, then you’ll need to know something about that class, so you’ll have to put its declaration into header.
Another problem is that class represents some kind of concept, so picking unique name should be fairly trivial. If you have many different classes with SAME name, you might have a design problem – your classes do not represent unique concepts, and you create too many classes needlessly.