Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it safe to cast this to a base-class pointer?
    text
    copied!<p>I'm currently learning C++, and this time I was messing with pointers, and studying the <code>this</code> pointer and polymorphism. My question is, is the conversion below safe, I know that basically I can access <code>m_uConnectedUsers</code> directly from <code>CUser</code> class because of 'public', but I may find an occasion where it will be needed, and I would like to know the opinion of you professionals about it.</p> <pre><code>#include &lt;windows.h&gt; #include &lt;iostream&gt; using namespace std; class CUserCounter { public: CUserCounter(); virtual ~CUserCounter(){}; BOOL m_bEmpty; u_long m_uConnectedUsers; }; CUserCounter::CUserCounter() { m_bEmpty = TRUE; m_uConnectedUsers = 0; } class CUser : public CUserCounter { public: CUser(LPCTSTR szName, BOOL bConnected, BOOL bChatting = FALSE ); virtual ~CUser(){}; BOOL m_bConnected; BOOL m_bIsChatting; TCHAR szCharName[32]; bool IncreaseMoverMeter( unsigned uMeters ); }; CUser::CUser( LPCTSTR szName, BOOL bConnected, BOOL bChatting ) { if( szName ) { if( strlen( szName ) &gt; 30 ) strcpy( szCharName, "Invalid" ); else strcpy( szCharName, szName ); } m_bConnected = bConnected; m_bIsChatting = bChatting; } bool CUser::IncreaseMoverMeter( unsigned uMeters ) { //is it safe? how does it works CUserCounter* pUserCounter = (CUserCounter*)this; if( pUserCounter ) { pUserCounter-&gt;m_uConnectedUsers++; return true; } return false; } int main( int argc, char *argv[] ) { CUser *pUser = new CUser( "Jonh", FALSE ); std::cout &lt;&lt; pUser-&gt;IncreaseMoverMeter( 4 ); system("pause&gt;nul"); return EXIT_SUCCESS; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload