junw2000@gmail.com wrote:
> 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() ;
>
> }
>
> Thanks.
>
> Jack
2 more cents: because 100 is all the code can realistically hope to get
in the constructor, the following functionally equivalent code for A can
make its intention clear without extra comments:
class A
{
public:
A() { data = getNumberOfA(); }
void setvalue() { data = getnumber(); }
void print() { cout << data << endl; }
private:
virtual int getnumber() { return getNumberOfA(); }
int getNumberOfA() { return 100; }
int data;
};
Hope this will help
-Pavel