C
CoolPint
I read that the return type has to be exactly same for a virtual
function to be overriden. While testing something, I discovered
something I cannot understand.
I cannot understand why the code below compiles.
I see that it won't compile if I have "virtual char & vtest() { }" in
Base class
and have "virtual const char & vtest() { }" in Derived class.
But it compiles if I have "virtual const char & vtest() { }" in Base
class and have "virtual char & vtest() { }" in derived class.
Why? What's going on?
Similarly, operator*() functions compiles as written, but always
returns const int & even I assign derived object to Base reference.
Please have a look at comments on function fun() to see what I mean.
Can anyone kindly explain why it compiles yet won't do dynamic
binding?
Thanks always (especially to you, Victor B.)
#include <iostream>
using std::cout;
using std::endl;
class CPtr {
public:
CPtr(int * a)tr(a) { };
virtual const int & operator*() const
{
return *ptr;
}
virtual const char & vtest() { }
protected:
int * ptr;
};
class Ptr: public CPtr {
public:
Ptr(int * a):CPtr(a) { };
virtual int & operator*() const
{
return *ptr;
}
virtual char & ttest() { }
};
void fun(CPtr & p)
{
// I was hoping this would work since a Ptr object is passed and
// dynamically it would bind to virtual int & operator*() const
// But it binds to virtual const int & operator*() const at compile
time
// Why?
// cout << ++(*p) << endl;
}
int main()
{
int i = 10;
Ptr pt(&i);
cout << ++(*pt) << endl;
fun(pt);
return 0;
}
function to be overriden. While testing something, I discovered
something I cannot understand.
I cannot understand why the code below compiles.
I see that it won't compile if I have "virtual char & vtest() { }" in
Base class
and have "virtual const char & vtest() { }" in Derived class.
But it compiles if I have "virtual const char & vtest() { }" in Base
class and have "virtual char & vtest() { }" in derived class.
Why? What's going on?
Similarly, operator*() functions compiles as written, but always
returns const int & even I assign derived object to Base reference.
Please have a look at comments on function fun() to see what I mean.
Can anyone kindly explain why it compiles yet won't do dynamic
binding?
Thanks always (especially to you, Victor B.)
#include <iostream>
using std::cout;
using std::endl;
class CPtr {
public:
CPtr(int * a)tr(a) { };
virtual const int & operator*() const
{
return *ptr;
}
virtual const char & vtest() { }
protected:
int * ptr;
};
class Ptr: public CPtr {
public:
Ptr(int * a):CPtr(a) { };
virtual int & operator*() const
{
return *ptr;
}
virtual char & ttest() { }
};
void fun(CPtr & p)
{
// I was hoping this would work since a Ptr object is passed and
// dynamically it would bind to virtual int & operator*() const
// But it binds to virtual const int & operator*() const at compile
time
// Why?
// cout << ++(*p) << endl;
}
int main()
{
int i = 10;
Ptr pt(&i);
cout << ++(*pt) << endl;
fun(pt);
return 0;
}