Hack the virtual table of a C++ object without a reference
<p>I know this question was asked here before but it is not exactly what I need, and as much as I try to manipulate the answers from <a href="https://stackoverflow.com/questions/1542108/how-to-hack-the-virtual-table">this thread</a> I cannot get the result I'm looking for.
So basically what I want to do is manipulate the virtual table in a C++ object so when calling one of the object's function it will call a different function
It is only for educational purposes of course.
my code is like that:</p>

<pre><code>class Animal
{
private:
    int height;
    int length;
    int type;

public:
    virtual void makeNoise()
    {
    }

    virtual void sleep()
    {
    }
};
</code></pre>

<p>Dog inherits from Animal such as:</p>

<pre><code>class Dog : public Animal
{
public:

    virtual void sleep() override
    {
        cout &lt;&lt; "Going to sleep for Dog" &lt;&lt; endl;
    }

    virtual void makeNoise() override
    {
        cout &lt;&lt; "bark bark" &lt;&lt; endl;
    }
};
</code></pre>

<p>Theres another class A:</p>

<pre><code>class A
{
public:

    virtual void doSomething(void)
    {
        cout &lt;&lt; "did nothing" &lt;&lt; endl;
    }
};
</code></pre>

<p>The function Hack is the function I want to override A->doSomething()</p>

<pre><code>void Hack()
{
   cout &lt;&lt; "Hacked!" &lt;&lt; endl;
}
</code></pre>

<p>main function:</p>

<pre><code>void main()
{

   int x = 0, y = 0, z = 0;
   A* a = new A();
   Animal * dog = new Dog();

   someFunctionToManipulateVirtualTable(dog); //function get an object of type Dog but should hack into an object of type A's vtable

   a-&gt;doSomething(); //should print "Hacked!"

}
</code></pre>

<p>Now the question is what should I do here:</p>

<pre><code>void someFunctionToManipulateVirtualTable(Animal * dog)
{ 
     //some code to manipulate main's local variable a (of type A).
}
</code></pre>

<p>So far, I have tried unsuccessfully , to get a's pointer through the dog reference from main, then get the virtual table pointer and override it with Hack's address, problem is , virtual table are in a read-only address location, I do manage to hack the vtable with local instances of A class, just with some pointer manipulation on the local instances..</p>

<p>Any lead on this will be awesome.
Thanks</p>