C++ question

Malte Starostik malte at kde.org
Wed Sep 25 22:03:42 BST 2002


On Wednesday 25 September 2002 14:34, Allan Sandfeld Jensen wrote:
> On Wednesday 25 September 2002 13:35, David Faure wrote:
> > On Wed, 25 Sep 2002, Michael Goffioul wrote:
> > > Can I call a pure virtual function in the constructor of the abstract
> > > class? That is
> > >
> > > class A
> > > {
> > > public:
> > >    A() { func(); }
> > >    virtual void func() = 0;
> > > };
> >
> > Impossible. When A is built, there is not yet a reimplementation of
> > func() registered in the vtable. This is a good way to see the nice "pure
> > virtual method called".
> > You have to simplify the constructors, and add some virtual init() that
> > does the job, for instance.
>
> Well almost impossible. rtti is active. So in case you know all possible
> children, you can just write a switch to call the right function.
RTTI is active, but since the object *is* only a Base in Base's ctor, RTTI 
returns Base's type info in Base's ctor, even when constructing a Derived. 
Everything else would be inconsistent and non-conforming:

#include <iostream>

class A
{
public:
	A() { std::cerr << "ctor: " << typeid( *this ).name() << std::endl; }
	virtual ~A() {}

	void f() { std::cerr << "member function: " << typeid( *this ).name() << 
std::endl; }
};

class B : public A
{
public:
	B() : A() {}
};

int main()
{
	B b;
	b.f();
}

outputs
ctor: 1A
member function: 1B

(note that gcc uses the mangled name in std::type_info::name())

<quote ISO/IEC 14882:1998>
[12.7, ยง4]
The typeid operator (5.2.8) can be used during construction or destruction 
(12.6.2). When typeid is used in a constructor (including from the 
mem-initializer for a data member) or in a destructor, or used in a function 
called (directly or indirectly) from a constructor or destructor, if the 
operand of typeid refers to the object under construction or destruction, 
typeid yields the type_info representing the constructor or destructor's 
class. If the operand of typeid refers to the object under construction or 
destruction and the static type of the operand is neither the constructor or 
destructor's class nor one of its bases, the result of typeid is undefined.
</quote>
The following paragraph states the same for dynamic_cast used in ctors and 
dtors. So, RTTI will definately not help you here. If it does, your compiler 
is wrong.

-Malte
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: signature
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20020925/57e47609/attachment.sig>


More information about the kde-core-devel mailing list