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 remains
Edit 2: Added common.h
Edit 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