Group: comp.lang.c++
From: Kira Yamato
Date: Saturday, February 16, 2008 4:12 PM
Subject: Re: Call virtual function in constructor

On 2008-02-16 14:25:25 -0500, junw2000@gmail.com said:

> Is there any problem if call virtual function in constructor? For
> example:
>
> class A
> {
> public:
> A()
> {
> setvalue();
> }
>
> setvalue()
> {
> data = getnumber();
> }
>
> print() { cout << data << endl;
>
> private:
> virtual int getnumber() {return 100;}
> int data;
> }
>
> class B : public A
> {
> public:
> B() { }
>
> private:
> virtual int getnumber() {return 22222;}
>
> }
>
> int main()
> {
> A test1;
> test1.print() ;
>
> B test2;
> test2.print() ;
>
> }

Technically, it's perfectly fine to call virtual functions in the
constructor as long as you understand that it will not invoke any
possible derived-class's overriding version of the same method. Also,
your compiler will complain if you're calling a pure virtual function.

However, semantically speaking, it seems weird why you would want to
invoke a method that your object wishes to override. I can't pinpoint
it yet, but it seems like a bad design. Sorry for being so vague.
Perhaps an expert can help point out the problem in a clear way.

--

// kira

Safety Articles | Usenet Groups | Usenet News | Bluegrass