Reputation: 3247
I hae written the following code:
class Object
{
public:
Object()
{}
};
template <class T>
class Reg : public Object
{
T val,val_new;
public:
Reg(T initval)
{
super( );
val=initval;
}
};
The error in the code is
t.cpp: In constructor 'Reg<T>::Reg(T)':
Line 15: error: there are no arguments to 'super' that depend on a template parameter,
so a declaration of 'super' must be available
compilation terminated due to -Wfatal-errors.
How can i eliminate the error?
Upvotes: 0
Views: 121
Reputation: 145389
class Object
{
public:
Object() {}
};
template <class T>
class Reg : public Object
{
T val,val_new;
public:
Reg(T const& initval)
: val( initval )
{}
};
There is no super
in standard C++. Some compilers offer it as a language extension, but in standard C++ if you want a generic name for “the” base class, then you have to typedef
it. For example, in class Reg
you can typedef Object Base;
.
The construction : val( initval )
is a constructor initializer list, where essentially you call constructors of members and base classes, avoiding default construction.
Finally, the const&
, passing by reference, avoids time-consuming and memory-consuming copying of the actual argument; it's another thing that's different in C++ (compared to Java, which I’m assuming that you’re coming from).
Upvotes: 5
Reputation: 51525
class Object
{
public:
Object()
{}
};
template <class T>
class Reg : public Object
{
T val,val_new;
public:
Reg(T initval) : Object() // initializer list
{
val=initval;
}
};
Upvotes: 2