D
David Scarlett
Hi all,
I've got a question regarding overriding const member functions with
non-const functions.
Let's say I've got a base class defined as follows:
/*******************/
class Foo
{
public:
Foo();
virtual ~Foo();
virtual void Run() const;
virtual void DoSomething();
}
/*******************/
Now, what I want to do is create another class derived from it, and
override the Run() method. However, I will need to call DoSomething()
from this new version of Run(), even though Run() is const and
DoSomething() is not. I'm not concerned about whether I should be
modifying a const object, because the only non-const behaviour
DoSomething() exhibits is logging related.
So here are two ways I can think of doing it. Both compile under
Microsoft VC++6, but I'm still wondering whether the first method in
particular is ISO C++ compatible (as I wasn't expecting it to
compile)...
/*******************/
class Bar1 : public Foo
{
public:
Bar1();
virtual ~Bar1();
// Overriding const Run() with non-const method.
virtual void Run() {DoSomething();}
virtual void DoSomething();
}
class Bar2 : public Foo
{
public:
Bar2();
virtual ~Bar2();
virtual void Run() const {const_cast<Bar2*>(this)->DoSomething();}
virtual void DoSomething();
}
/*******************/
So do these follow Standard C++, and what are people's opinions on
which is the better way to do it?
Thanks.
I've got a question regarding overriding const member functions with
non-const functions.
Let's say I've got a base class defined as follows:
/*******************/
class Foo
{
public:
Foo();
virtual ~Foo();
virtual void Run() const;
virtual void DoSomething();
}
/*******************/
Now, what I want to do is create another class derived from it, and
override the Run() method. However, I will need to call DoSomething()
from this new version of Run(), even though Run() is const and
DoSomething() is not. I'm not concerned about whether I should be
modifying a const object, because the only non-const behaviour
DoSomething() exhibits is logging related.
So here are two ways I can think of doing it. Both compile under
Microsoft VC++6, but I'm still wondering whether the first method in
particular is ISO C++ compatible (as I wasn't expecting it to
compile)...
/*******************/
class Bar1 : public Foo
{
public:
Bar1();
virtual ~Bar1();
// Overriding const Run() with non-const method.
virtual void Run() {DoSomething();}
virtual void DoSomething();
}
class Bar2 : public Foo
{
public:
Bar2();
virtual ~Bar2();
virtual void Run() const {const_cast<Bar2*>(this)->DoSomething();}
virtual void DoSomething();
}
/*******************/
So do these follow Standard C++, and what are people's opinions on
which is the better way to do it?
Thanks.