I intend to have several derived classes that have the same function that utilizes the this keyword to referred to objects in the derived classes. The issue is that when the function is defined in the base class, this refers to base class objects instead of derived class objects.
template< typename Type >
class ListClass
{
protected:
static std::stack< Type > clipboard; // For temporarily storing objects for copy-paste.
public:
void cpy(); // Copies object to clipboard
};
// Define ListClass::clipboard
template < typename Type >
std::stack< Type > ListClass< Type >::clipboard;
// Copies object to clipboard
template < typename Type >
void ListClass< Type >::cpy()
{
if ( !clipboard.empty() )
{
clipboard.pop();
}
clipboard.push( *this ); // This is where the problem
}
My current solution is to makes ListClass::cpy a static generic function and then have it called inside a derived class function.
The issue is that when the function is defined in the base class, this refers to base class objects instead of derived class objects.
That is correct, but remember you don't need to always use the *this pointer to access the current (derived) member functions or member variables. If the derived class hasn't overloaded the base class member you can access the base class member by omitting the *this pointer. If the derived class has overloaded the base class member then you need to properly scope the base::member.