0

I need some help here, could you tell me how I can get p2 variable content? I can get variables through t1 and p1 but I want to use p2 to get health and mana values.

#include <iostream>

using namespace std;

class Mage{
public:
    int health;
    int mana;
    Mage(int health, int mana){
        this->health = health;
        this->mana = mana;
    }
};

int main(){

    Mage t1 = Mage(1,1);
    Mage *p1 = &t1;
    Mage **p2 = &p1;

    cout << t1.health << endl;
    cout << p1->health << endl;
    cout << "how to print variable content with p2?" << endl;

    return 0;
}
6
  • 4
    how about (*p2)->health ? Commented Apr 24, 2017 at 16:22
  • 6
    @Beginner has the right of this, but if you find yourself wandering into pointers to pointers outside of a trivial education example, ask yourself "Why am I doing this again?" It's rare that you need more than one level of indirection, and when it crops up, a reference to the pointer (Mage * &p2) is probably a better option. Commented Apr 24, 2017 at 16:29
  • @Beginner it worked, thanks Commented Apr 24, 2017 at 16:35
  • you're welcome and godspeed for your Mages conquests :) Commented Apr 24, 2017 at 16:38
  • @user4581301 2 levels of indirection for pointers is rare, yes. But if for example you are iterating over a std::vector of std::unique_ptr, (*it)->foo() needs 2 levels of indirection, there is no other way around it. Commented Apr 24, 2017 at 16:48

2 Answers 2

2

Use

cout << (*p2)->health << endl;

The * has two meanings: to declare a pointer and to dereference a pointer. But since -> has higher precedence than * you need to put *p2 into backets.

Sign up to request clarification or add additional context in comments.

Comments

1

Your example suggests that you are looking for a single operator that dereferences two times at once. There is none in C++.

Two ways to achieve what you want. The first has already been mentioned and goes

std::cout << (*p2)->health << std::endl;

The second can be found by noting that p1->health is equivalent to (*p1).health. Hence, (*p2)->health is equivalent to (**p2).health. In a row:

std::cout << t1.health << std::endl;
std::cout << (*p1).health << std::endl;
std::cout << (**p2).health << std::endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.