M
mr.xiaofan.li
Hi,
I have been totally confused about the covariant return type feature
in C++. Below is an example code I wrote that doesn't compile with g++
4.1.2 (on Fedora 8)
class virt_base
{
public:
virt_base()
{
}
virtual ~virt_base()
{
}
virtual virt_base* cut()
{
return new virt_base();
}
void say_hi()
{
cout <<"hi!!! " <<endl;
}
};
class virt_derived
: public virt_base
{
public:
virt_derived()
{
}
~virt_derived()
{
}
virtual virt_derived* cut()
{
return new virt_derived();
}
void say_hi()
{
cout <<"HI!!!! " <<endl;
}
};
int main()
{
virt_base* my_virt_derived = new virt_derived();
virt_derived* new_virt_derived = my_virt_derived->cut(); // g++
complains here: invalid
//
conversion from 'virt_base*' to
//
'virt_derived*'
new_virt_derived->say_hi();
}
I have been totally confused about the covariant return type feature
in C++. Below is an example code I wrote that doesn't compile with g++
4.1.2 (on Fedora 8)
class virt_base
{
public:
virt_base()
{
}
virtual ~virt_base()
{
}
virtual virt_base* cut()
{
return new virt_base();
}
void say_hi()
{
cout <<"hi!!! " <<endl;
}
};
class virt_derived
: public virt_base
{
public:
virt_derived()
{
}
~virt_derived()
{
}
virtual virt_derived* cut()
{
return new virt_derived();
}
void say_hi()
{
cout <<"HI!!!! " <<endl;
}
};
int main()
{
virt_base* my_virt_derived = new virt_derived();
virt_derived* new_virt_derived = my_virt_derived->cut(); // g++
complains here: invalid
//
conversion from 'virt_base*' to
//
'virt_derived*'
new_virt_derived->say_hi();
}