#include <iostream>
class A {
public:
virtualvoid a() = 0;
};
class B {
public:
void a() {}
virtualvoid b() = 0;
};
class C : public A, public B {
public:
C() {
std::cout << "Hello World" << std::endl;
}
void b() {}
};
static C c;
int main() {
return 0;
}
However, this code doesn't compile, even though C::a() should be defined. Why doesn't this work, and how can I fix it?
can you have static global variables? even if you can it doesnt make any sense. it wont be deleted anyways because it doesnt go out of scope. as to your problem... using ideone i figured it out.
#include <iostream>
class A {
public:
virtualvoid a() {};
};
class B {
public:
void a() {}
virtualvoid b() {};
};
class C : public A, public B {
public:
C() {
std::cout << "Hello World" << std::endl;
}
void b() {}
} c;
int main() {
return 0;
}
you cant have virtual void identifier() = 0;
you need virtual void identifier() {}
@TC: I think the problem is closer to 'what a() do you have?' You inherit from two classes that define it. I'll try to look at this again later when I have more time to actually find the problem.
@DTSCode: Why can't you use = 0? That's the syntax for a pure virtual method.
In any case, static global scope was IIRC an old C way of created variables local to a compilation unit; in C++ I believe you usually use an anonymous namespace.
@ DTS: that has a slightly different meaning. He wants a() to be pure virtual in the a class... whereas that's not the case with your class.
@ OP:
The problem is because there are two different vtables here. One for the A class and one for the B class. Virtual functions from one do not "merge" with functions from the other unless they're part of the same inheritance tree. That is... C sees B::b as a non-virtual function whereas it sees A::b as a pure virtual function. It does not see B::b as an implementation of A::b.
To accomplish this, you'll need to ensure that both classes with implementations are part of the same tree (ie: they have a common parent).
Or if that's not an option, you can explicitly call B::a() from C::a() :
1 2 3 4 5 6 7 8
class C : public A, public B {
public:
C() {
std::cout << "Hello World" << std::endl;
}
void b() {}
void a() { B::a(); } // <-
};
im going to stop posting here because this is now going over my head. im still too new to oop to understand what was told to me :} and yeah why was my post reported?