I’m new to OO based programming, so a silly question:
I’ve created a class called algorithmObject. Basically, it has a bunch of functions associated with it.
I’ve created a QT GUI and I want to create a public object of type algorithmObject, since I want to be able to access the member functions in various onClick events.
So in my GUI.h file, I have:
public:
algorithmObject Object1;
In my GUI.cpp file, I’m trying to initialize it by:
Object1 = algorithmObject();
I’m using MS VS 2010 and I get a compiler error:
error C1903: unable to recover from previous error(s); stopping compilation
error C2065: ‘Object1’ : undeclared identifier
If I don’t include :
Object1 = algorithmObject();
in my GUI.cpp file and just hope for the GUI constructor to create the object for me, I get the same error.
I guess, I am not initializing my object correctly in the .cpp file somehow. Can someone suggest what is the right process?
My algorithmObject files are outlined below:
algorithmObject.h
#include <iostream>
#include <fstream>
class algorithmObject
{
public:
algorithmObject (void);
~algorithmObject (void);
void function1 (int parameter);
void function2 ();
}
algorithmObject.cpp
#include "algorithmObject.h"
algorithmObject::algorithmObject(void)
{
}
void algorithmObject::function1(int parameter)
{
//do something
}
void algorithmObject::function2()
{
//do something
}
algorithmObject::~algorithmObject(void)
{
}
If I however, don’t include any definition in the GUI.h file and just define my algorithmObject within a single function in the GUI (algorithmObject Object1;) , I am able to correctly access the functionality of my class. But the problem is that the object is local to that function and I cannot access it from any other functions of the GUI.cpp file which is extremely crucial for me …
You need to include
algorithmObject.hingui.h, so by the time the compiler sees the code that tries to use analgorithmObject, it’s already seen the declaration for thealgorithmObjectclass.It’s possible to avoid this by always including
algorithmObject.hin the source file before you try to use it, so you’d need to have:Although this was fairly standard practice in a lot of C for a long time, I (personally) consider it fairly error-prone and fragile, so I generally prefer that if a header depends on other headers, it includes them itself, so there are no prerequisites to meet when including it in a source file.