special kind of virtual method

  • Thread starter Thread starter Zeng
  • Start date Start date
Z

Zeng

I often run into situation where I would like to have a method such as that
has derived behavior similar to destructors in c++, is that possible?

public BaseClass
{
private int m_dataInBase;
public BaseClass()
{m_dataInBase = 0}
public void SetDataBase( int val ) { m_data = val; }
virtual public void ClearData()
{
m_dataInBase = 0;
}
}

public DerivedClass
{
private int m_dataInDerived;
public DerivedClass()
{ m_dataInDerived = 0; }
public void SetDataDerived( int val ) { m_data = val; }
override public void ClearData()
{
base.ClearData(); // I WANT TO REINFORCE THIS CALL OR AUTOMATE THIS
IN THE BaseClass
m_dataInDerived = 0;
}
}
 
You can always make the base method not virtual and have it call a virtual
method after it's done whatever needs to be done first in the base..

Niall
 
I often run into situation where I would like to have a method such as that
has derived behavior similar to destructors in c++, is that possible?

public BaseClass
{
private int m_dataInBase;
public BaseClass()
{m_dataInBase = 0}
public void SetDataBase( int val ) { m_data = val; }
virtual public void ClearData()
{
m_dataInBase = 0;
}
}

public DerivedClass
{
private int m_dataInDerived;
public DerivedClass()
{ m_dataInDerived = 0; }
public void SetDataDerived( int val ) { m_data = val; }
override public void ClearData()
{
base.ClearData(); // I WANT TO REINFORCE THIS CALL OR AUTOMATE THIS
IN THE BaseClass
m_dataInDerived = 0;
}
}
Overriding means that you 'know how to handle the thing better' than
the base class...
So you will have to manually call base.xxx();

You might want to take a look at the Dispose pattern...

Linebreaks!
http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconfinalizedispose.asp
 
that won't work if the derivation hierarchy is bigger. In C++ gets called,
the destructors from the leaf class to the base class in the hierarchy get
called automatically.
 
But that only happens for destructors in C++, the virtual and pure virtual
methods don't follow that behaviour. As NULL said, when you override, your
basically declaring that the base class doesn't understand how to operate
properly in this context. If there was a type of virtual that forced the
base call, it could become very annoying if you are trying to override the
method so that you can set up some data before the base does its thing.

Just as an aside, aren't you talking about constructos as the analogy here,
not destructors? Constructors run base->derived, which is what you're
describing.
 
Back
Top