Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object==this in c++

Tags:

c++

oop

I have spent a great deal of time programming in Java and a decent amount of time writing c++, but I have run into an issue I haven't been able to solve. In a Java class I can simply write the following,

public void doOperation(object a)
{
    if(a != this)
    {
        set(a); // just some method that sets this.a = object.a
    }

    doOperation();
}

public void doOperation()
{
   this.a = pow(this.a,3);
}

The part I am having trouble implementing in c++ is the if statement where I check if the argument object is equal to this. I have tried this in c++

object::doOperation(object a)
{
    if(a != this)
    {
        set(a);
    }

    doOperation();
}

object::doOperation()
{
    this->a = pow(this->a,3)
}

The error I get reads, "no match for ‘operator!=’ (operand types are ‘object’ and ‘object* const’)". Thanks in advance for anybody who can help!

like image 829
jlack Avatar asked Jan 29 '26 22:01

jlack


1 Answers

You can simply pass "a" by reference, take a pointer to "a" and compare it with "this", like so:

object::doOperation(object & a)
{
    if(&a != this)
    {
        set(a);
    }

    doOperation();
}

object::doOperation()
{
    this->a = pow(this->a,3)
}

This is a standard way that people would e.g. implement copy assignment operators in C++. It's not always done this way, but often the implementation of that will take a const reference to an object, and use a check against "this" to prevent self assignment.

Edit: Let me try to take a broader view, which might be more useful to you.

In Java, objects are implicitly passed around by reference and not by value, and they are garbage collected also, automatically destroyed when no-one needs them anymore.

The closest way to get that kind of semantics in C++ is to pass around std::shared_ptr<A> when in java you would have passed A. Then, when you need to compare against this, you can use the get method to get a raw pointer from the shared pointer and compare it literally against this. OR, if you use the std::enable_shared_from_this template when you define your class, you can use shared_from_this to get a shared_ptr<A> to this at any point in your member functions, and compare the shared_ptr's directly.

I'm assuming you are using C++11, otherwise you would use boost headers for that stuff.

Note also the stuff about "weak_ptr" which you might need to use if you have cyclic references.

like image 187
Chris Beck Avatar answered Jan 31 '26 10:01

Chris Beck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!