I was trying to understand how the this
and the *this
keywords work in C++. From my understanding, this
returns a pointer to the current instance of the object for which it is called, whereas *this
returns a clone of the very same instance.
I saw a version of the below code being used in an algorithms question in a different, unrelated place. I have only kept the parts of the code that pertain to my query.
#include <iostream>
class Base
{
public:
int a, b;
void haha()
{
std::cout << "haha!!!" << std::endl;
}
};
class Derived : public Base
{
public:
int c, d;
void method()
{
Base b(*this);
b.haha();
}
};
int main()
{
Derived d;
d.method();
return 0;
}
I am not able to wrap my head around how *this
(a copy of the current Derived
class object) is being used to instantiate an object of the Base class.
What is the OOP principle in play here?