Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The code you posted will not compile because the compiler has no Idea what <code>derived</code> class is while compiling the code for <code>class Base</code>. the <code>this</code> pointer is a pointer that is implicitly passed to every non static member function of a class its how that function can access member attributes of the it's instance. In a <code>Base</code> class member function <code>this</code> has type <code>Base *</code> In a <code>const</code> member function it will have the type <code>const Base *</code>.</p> <p>Also the <code>this</code> is a non l-value that means you can not assign a value to it.</p> <p>The following is from the C++ standard about the this pointer:</p> <blockquote> <p>9.3.2 The this pointer</p> <p>In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.</p> </blockquote> <p>Now as for doing what you want to do in your question the following compiles</p> <pre><code>#include &lt;iostream&gt; class Base { public: void get(); }; class derived: public Base { public: void put() { std::cout &lt;&lt; "This is a bad idea" &lt;&lt; std::endl; } }; void Base::get() { //compiler knows what dervied class is static_cast&lt;derived *&gt;(this)-&gt;put(); } int main() { derived d; d.get(); return 0; } </code></pre> <p>output is : <code>This is a bad idea</code></p> <p>I recommend using virtual functions or templates to get the desired behaviour.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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