Re: Implementation of abstract classes
On 2008-09-21 16:55, Rune Allnor wrote:
On 20 Sep, 19:12, Erik Wikstr??m <Erik-wikst...@telia.com> wrote:
Just because a function is pure virtual does not mean it cannot be
implemented:
#include <iostream>
struct Base
{
virtual ~Base() = 0
{
std::cout << "~Base\n";
}
};
Can this be correct? The way I understand
virtual void foo() = 0;
is that the statement inituializes a NULL
pointer in the virtaul function table.
It this is correct your code above will
result in undefined behaviour.
Actually it is *not* a correct solution to Rune's problem, but not
because the reason you mentioned. The C++ standard does not mention
vtables or such things, it only defines what is supposed to happen and
leaves to the compiler to use the best technique to make it happen.
The "= 0" at the end of a function declaration means that the function
is pure virtual, and a class with a pure virtual function is abstract
(it can not be instantiated). This means that any derived classes have
to either implement the function or they will abstract too.
The reasons my code was not correct is that the standard does not allow
a pure function to be defined together with the declaration:
struct Foo
{
virtual void bar() = 0 { 1+1; } // Error
};
You can, however, provide the the definition separately:
struct Foo
{
virtual void bar() = 0;
};
void Foo::bar()
{
1 + 1;
}
You can also call a pure virtual function using a qualified expression:
struct Foo
{
virtual void bar() = 0;
};
void Foo::bar()
{
std::cout << "Foo::bar()\n";
}
struct Baz : public Foo
{
void bar()
{
std::cout << "Baz::bar()\n"
Foo::bar();
}
};
int main()
{
Foo* f = new Baz();
f->bar();
return 0;
}
Output:
Baz::bar()
Foo::bar()
--
Erik Wikstr??m