Re: Partial implementation in derived classes
Alex Vinokur wrote:
I tried to build program with partial implementation.
However a linker generates errors.
Is there any approach that enables to use partial implementation for
similar purposes?
------ foo.cpp ---
struct Base
{
virtual void foo1() = 0;
virtual void foo2() = 0;
};
struct Derived1 : public Base
{
void foo1() {}
void foo2(); // Not for use
};
What do you mean "not for use"? Why do you derive from a class that has a
virtual member function with that name if you don't want it to be used? If
a function that gets a pointer to the base class calls foo2() without
knowing that it's actually a Derived1 (which is what virtual member
functions are for), what would you expect to happen?
struct Derived2 : public Base
{
void foo1(); // Not for use
void foo2() {}
};
int main ()
{
Base* p1 = new Derived1();
Base* p2 = new Derived2();
// -----------------------
// I would like to get linkage error in the following cases:
// p1->foo2();
// p2->foo1();
How would that work? Virtual functions are resolved at run-time. You can't
get a compile-time error for an error that occurs at run-time. Consider:
Base* p;
int x;
std::cout << "Derived1 (1) or Derived2 (2)? "
std::cin >> x;
if (x == 1)
p = Derived1();
else if (x == 2)
p = Derived2();
std::cout << "foo1 (1) or foo2 (2)? "
std::cin >> x;
if (x == 1)
p->foo1();
else if (x == 2)
p->foo2();
Now how would the compiler know at compile-time what the user will choose?
But you could e.g. throw an exception in the derived class's implementation.