Topic: Problem with constructor in derived class, please help.
Author: xjzhu@math.uwaterloo.ca (Xiaojun Zhu)
Date: Sun, 6 Dec 1992 21:41:38 GMT Raw View
Dear C++ experts:
I am experiencing a problem when I am constructing a derived class. I think
I have narrowed down the problem.
The code segment and two scripts of compilation under AT&T C++ V3.0 and
GCC 2.2.2 are appended in the end of this message.
The problem lies in the constructor of the derived class D:
D(int s) { if(s>0) B<int>(s); else B<int>(-s); }
A simple change such as
D(int s) : B<int>((s>0)? s: -s) {}
or
D(int s) : B<int>(s) { if(s<0) _s=-s; }
will make the problem go away.
But I would very much like to know what's the problem with the constructor
in the original code.
Would you please help?
/************Code Segment Follows *********************/
/************ strange.h ***Cut Here *******************/
template<class S>
class B
{
S _s;
public:
B(S s) : _s(s) {}
~B() {}
};
class D : public B<int>
{
public:
D(int s) { if(s>0) B<int>(s); else B<int>(-s); }
~D() {}
};
/********************************************************/
/************ strange.C *********************************/
#include "strange.h"
main()
{
D x(-3);
}
/*********************************************************/
/*********************************************************/
Script of compilation under AT&T C++ V3.0
Script started on Sun Dec 6 16:19:57 1992
math[/u3/xjzhu/postnews][29] CC strange.C
CC strange.C:
"./strange.h", line 13: error: argument 1 of type int expected for B <int >::B__pt__2_i()
"./strange.h", line 15: warning: result of constructor call expression not used
"./strange.h", line 15: warning: result of constructor call expression not used
"./strange.h", line 13: sorry, cannot recover from earlier errors
2 errors
math[/u3/xjzhu/postnews][30] exit
script done on Sun Dec 6 16:20:31 1992
/***********************************************************/
/***********************************************************/
Script of Compilation under GCC 2.2.2
Script started on Sun Dec 6 16:27:08 1992
g++ strange.C
strange.h: In method `D::D (int)':
In file included from strange.C:1:
strange.h:15: too few arguments for constructor `B'
strange.h:15: in base initialization for class `D'
math[/u3/xjzhu/postnews][32] exit
math[/u3/xjzhu/postnews][33]
script done on Sun Dec 6 16:27:39 1992
/***********************************************************/