Accessing Static Method and Static bool in other class - c++

I have a base interface class:
class A
{
public:
ITask(){}
virtual bool Start()=0;
virtual void Update()=0;
virtual void Stop()=0;
};
I now have 2 other classes, that inherit from this
#include "A.h"
#include "C.h"
class B: public A
{
public:
bool Start(){}
void Update()
{
c.Start();
}
void Stop(){}
static bool m_run;
static void SetRun(bool run)
{
m_run = run;
}
private:
C c;
};
lastly I have a 3rd class:
#include "A.h"
#include "B.h"
class C : public A
{
public:
bool Start()
{
B::SetRun(false); // cant do this
B::m_run = false; // or this
}
void Update()
{
}
void Stop()
{
}
}
I have shaved down some of the code, for simplicity.
I dont understand why I cant access the static var in B. Do I need to make it a pointer or a ref?
I get 2 errors:
error C2653: 'B' : is not a class or namespace name
error C3861: 'm_run': identifier not found

Although you don't show it, I'm assuming that B.h includes C.h; otherwise the line C c; won't compile. This causes a circular dependency in the header files: B.h must be included before C.h, which must be included before B.h, which is impossible.
The easiest solution is to move the body of C::Start out of the definition of C, so that C.h does not need to include B.h. The function definition can go into a source file, or a separate header if you want to keep it inline.
Alternatively, you could modify B to contain a std::unique_ptr<C> rather than an instance of C, and implement a constructor (in a source file, or a separate header) that initialises it with new C. Then B.h only needs to forward declare class C; rather than including C.h.
A better solution, if possible, would be to rethink the relationships between the classes so that there isn't a circular dependency.
(UPDATE: while I was writing this answer, the question changed to show that B.h does indeed include C.h as I guessed.)

There is nothing wrong with your example code (after the edits), the problem must be somewhere else, like a failed include.

Related

Header files and multiple class usage (EDIT: forward declarations)

I have a problem where I have several header files, and I need to include each of them in each other. Obviously, this cannot be done, because when I compile, the error "include nested too deeply" is thrown - as this essentially asks the compiler to enter an infinite include loop.
I could fix it using void pointers, but this seems like bad coding practice to me.
Here is an example of what I am trying to do, to aid understanding:
File-A:
#include "File-B"
#include "File-C"
class A
{
public: B* p_B;
public: C* p_C;
};
File-B:
#include "File-A"
#include "File-C"
class B
{
public: A* p_A;
public: C* p_C;
};
File-C:
#include "File-B"
class C
{
public: B* p_B;
};
This just shows where each class declaration is needed. Surely there is a better solution to void*.
EDIT: I am already using include guards, this code is just to help you see what I am trying to do.
You should use include guards:
#ifndef _FILE_A_H_
#define _FILE_A_H_
// Contents of FileA.h...
#endif
Possibly, also use forward declarations to break cyclic dependencies between the definitions of your data structures.
In FileA.h:
class B; // No need to #include "FileB.h"
class A
{
public:
B* pB;
};
In FileB.h:
class A; // No need to #include "FileA.h"
class B
{
public:
A* pA;
};
If you are using pointers or references to the other classes, and no code in the header file, you can use forward declarations:
class A; // Forward declaration
class C; // Forward declaration
class B
{
public:
A* p_A;
C* p_C;
};
If code in the header file refers to any members of the other classes, you will have to include the entire definitions of the other classes.
I would use include guards, which only include a certain file once.
#ifndef FILE_A
#define FILE_A
class A
{
public: B* p_B;
public: C* p_C;
};
#endif
http://en.wikipedia.org/wiki/Include_guard
It only includes the header file once per file.
You can also use #pragma_once, although it is not standard.
In the case that doesn't work, you can use a forward declaration.
class B;
class C;
class A
{
public: B* p_B;
public: C* p_C;
};
This is why you have #include <> guards.
#ifndef _FILE_B
#define _FILE_B
#include "File-A"
#include "File-C"
class B
{
public: A* p_A;
public: C* p_C;
};
#endif

Base class undefined

I know it is one of the constant ask question
so i get this error
'WorldObject': [Base class undefined (translated from german)]
Here is the code which produce this error:
ProjectilObject.h:
#pragma once
#ifndef _PROJECTILOBJECT_H_
#define _PROJECTILOBJECT_H_
#include "GameObjects.h"
class ProjectilObject: public WorldObject
{
public:
ProjectilObject(IGameObject* parent,int projectiltype);
void deleteyourself();
protected:
virtual void VProcEvent( long hashvalue, std::stringstream &stream);
virtual void VInit();
virtual void VInitfromStream( std::stringstream &stream );
virtual void VonUpdate();
virtual void VonRender();
private:
vec3 vel;
float lifetime;
float lifetimeend;
vec3 target;
int m_projectiltype;
};
#endif
Here is the code file from the WorldObject class:
GameObjects.h:
#pragma once
#ifndef _GAMEONJECTCODE_H_
#define _GAMEONJECTCODE_H_
#include "IGameObject.h"
#include "Sprite.h"
#include "GamePath.h"
#include "HashedString/String.h"
#include "IAttribute.h"
#include "CharacterObjects.h"
#include "ProjectilObject.h"
[...]
class WorldObject: public IGameObject, public MRenderAble
{
public:
WorldObject(IGameObject* parent);
virtual bool IsDestroyAble();
virtual bool IsMageAble();
virtual bool IsRenderAble();
protected:
virtual void VProcEvent( long hashvalue, std::stringstream &stream);
virtual void VonUpdate();
virtual void VonRender();
virtual void VInit() =0;
virtual void VInitfromStream( std::stringstream &stream ) =0;
virtual void VSerialize( std::stringstream &stream );
vec3 poscam;
};
[...]
#endif
There are some other Classes in this file but they shouldn't interrupt, I think.
Maybe there is a tiny error I didn't saw but I don't understand why this error is produced. When you need more of the code feel free to ask because i think it would only disturb.
If you have any source file that includes GameObjects.h before ProjectilObject.h or does not include ProjectilObject.h directly, then the compiler will first find the declaration of ProjectilObject through the include in GameObjects.h before knowing what WorldObject is. That is because GameObjects.h first includes ProjectilObject.h and then declares WorldObject. In that case the include of GameObjects.h present in ProjectilObject.h won't work because _GAMEONJECTCODE_H_ will be already defined.
To avoid this, either be sure to include ProjectilObject.h instead of GameObjects.h in your source file, or use forward declarations.
It's hard to answer this question without looking at the whole code. Even a misplaced brace could count. Check your namespaces - are you sure the WorldObject is in the same namespace?
I suggest you use the #pragma message by placing it near the WorldObject definition and checking the compiler output:
#pragma message ("World object is defined")
If it does not show up, move the pragma to the parent .h file and check the compiler output again. With this you can easily locate the error.
class WorldObject;
class ProjectilObject: public WorldObject
You are forward declaring WorldObject, but to inherit from a class you need the definition, so you have to include the header of WorldObject.
In my case: i delete derived class include from base class header file.
for example:
file 1 :
#include "B.h"
-> A()
file 2:
-> B() : A()
solution : delete #include "B.h" from file1

C++ inheritance: virtual member needs redeclaring?

I'm sure this question has already been asked in one form or another, but I couldn't find the clue. Please consider the following C++-code:
// A.h
class A
{
public:
A();
virtual ~A();
virtual void setVisibility(bool v);
virtual bool setVisibility();
protected:
bool visibility;
};
// B.h
class B : public A
{
public:
B();
virtual ~B();
};
// C.h
class C : public B
{
public:
C();
virtual ~C();
virtual void setVisibility(bool v);
virtual bool setVisibility();
};
// A.cpp
#include "common.h"
A::A() {}
A::~A() {}
void A::setVisibility(bool v) { this->visibility = v; }
bool A::setVisibility() { return this->visibility; }
// B.cpp
#include "common.h"
B::B() {}
B::~B() {}
// C.cpp
#include "common.h"
C::C() {}
C::~C() {}
void C::setVisibility(bool v) { /* do nothing */ }
bool C::setVisibility() { return false; }
// common.h - does nothing else than joining the header files together
#include "A.h"
#include "B.h"
#include "C.h"
calling:
C* myC = new C();
cout << "Set visibility true" << endl;
myC->setVisibility(true);
I tried several things. If I declare both methods virtually in C, it compiles but I get a segmentation fault at myC->setVisibility(true). If I remove the declaration (which shouldn't be necessary anyway, as they're inherited from B and A, right?), then it tells me that C doesn't have these methods.
And I don't want to reimplement the methods in B. If I declare them everywhere including B, it tells me that there's no implementation of these methods in B.
What should I do now? I need virtual, because I'm not always gonna use C as variable type in the calling example.
I'm using GCC on a 64 bit machine.
Edit: Corrected the copy/paste-mistake. I named the classes A, B and C for simplicity and didn't copy the code correctly. But unfortunately, the problem remainsEdit 2: Added common.hEdit 3: Hmm... copying this code actually works fluently. But the architecture is the same. Except that I compile my code into a shared library using the flags -shared -fPIC. The calling code is in the application that uses this library. Nothing else is different. Gotta check again.
Thanks for any tips pointing me to the right direction. regards
in C.cpp, don't define A::setVisibility(), it should be C::setVisibility()
In C.cpp, you're defining A::setVisibility, not C::setVisibility.
You can change your class C to:
// C.h
class C : public B
{
public:
C();
virtual ~C();
using A::setVisibility;
virtual bool setVisibility();
};
This will "reintroduce" all kinds of setVisibility defined in A.
The other answers are all correct before the correction. But it's not the solution to the problem. There actually isn't any problem at all. The problem lies in my implementation of the setVisibility-method, that's where the segfault occurs. Therefore the solution can't be found here.
Thanks to all who tried to help!
regards

multiple declaration error- virtual functions

I have observer.h , client.h and field.h files.
In observer.h there is Subject class which has
// observer.h
class Subject {
public:
virtual ~Subject(){};
Subject(){};
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify(bool _value);
virtual bool getCheckedIn(){};
private:
vector < Observer* > _observers;
};
#ifndef CLIENT_H
#define CLIENT_H
#include "Field.h"
class Client : public Subject {
public:
Client(string _name, Field *_field) : client_name(_name) ,field(_field) , checked_in(false) {}
void setCheckedIn(bool _value){
checked_in = _value;
Notify(_value);
}
void enterRow(string _row_name){
field->deneme();
setCheckedIn(true);
}
bool getCheckedIn(){ return checked_in;}
private:
bool checked_in;
string client_name;
Field *field;
};
#endif // CLIENT_H
#ifndef Field_H
#define Field_H
#include "CreateRow_absFac.h"
#include "observer_pattern.h"
#include <vector>
#include <string>
using namespace std;
// Template Class
class Field{
public:
Field();
// Template method
void field_creator();
virtual void setAbstractRow() = 0;
protected:
FarmFactory *abstract_row1;
FarmFactory *abstract_row2;
FarmFactory *abstract_row3;
Rows *row1 ;
Rows *row2 ;
Rows *row3 ;
Sensor sensor1;
};
When compiled , got this error :
ld: duplicate symbol Subject::Notify(bool) in /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/Field.o and /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/main.o
If I remove virtual functions it compiles without error. What is the problem with virtual functions ?
We can't actually see it here, but the problem is probably that you defined Subject::notify(bool) in a header file (your observer.h just declares it, it doesn't define it) and you included that header file in both Field.cpp and main.cpp, so you get multiple definitions. The fix is to move the definition into a source file so its only defined once.
General rule -- DECLARE things in header files, DEFINE them in non-header source files. Note that include guards are irrelevant here -- they prevent something being declared multiple times in a single compilation unit, but what's needed is to avoid defining something multiple times in different compilation units.
Try keeping header guards even for your observer.h. BTW, Why aren't you overriding virtual functions in the derived class ?
Apparently you have an ODR violation. Why did you get away with non-virtual functions? Possibly because you defined them inline (e.g. in class). As it was suggested, check the include guards and function definitions.

Two classes and inline functions

I have two classes and both of them uses some of the other class, on example:
// class1.h
class Class1;
#include "class2.h"
class Class1 {
public:
static Class2 *C2;
...
};
// class2.h
class Class2;
#include "class1.h"
class Class2 {
public:
static Class1 *C1;
...
};
And when I define it like in example above, it works (I also have some #ifndef to avoid infinite header recurency). But I also want to add some inline functions to my classes. And I read here that I should put definition of inline function in header file, because it won't work if I'll put them in cpp file and want to call them from other cpp file (when I do it I get undefined reference during linking). But the problem here is with something like this:
// class1.h
...
inline void Class1::Foo() {
C2->Bar();
}
I get error: invalid use of incomplete type ‘struct Class2’.
So how can I do it?
You need to delay including the header, but then include it and define your inline methods. By doing this in each header, they are self-sufficient and including one will always include the other, with include guards preventing infinite recursion.
A.hpp
#ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
#define INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
struct B;
struct A {
B* p;
void foo();
};
#include "B.hpp"
inline
void A::foo() {
if (p) p->bar();
}
#endif
B.hpp
#ifndef INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
#define INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
struct A;
struct B {
A* p;
void bar();
};
#include "A.hpp"
inline
void B::bar() {
if (p) p->foo();
}
#endif
You have it mix'd up. What you want is:
// class1.h
class Class2;
class Class1 {
public:
static Class2 *C2;
...
};
// class2.h
class Class1;
class Class2 {
public:
static Class1 *C1;
...
};
And include the respective headers in the source. The line:
class Class1; // or Class2
Declares an incomplete type, and you can have pointers and references to incomplete types. Upon usage, though, it needs to be complete. So just say "hey it'll exist!" in the header, and in the source tell it what it is.
My suggestion is that you place common methods and members into a base class, then derive C1 and C2 from the base class. This may fix the circular dependency issue.