简体   繁体   中英

Pointer to an object that has a pointer member

Are pointers to pointers legal in c++? I've come across this SO question: Pointer to Pointer to Pointer

But the answers aren't clear if it is legal c++ or not. Let's say I have:

class A{
public:
    void foo(){
        /* ect */
    }
};

class B{
public:
    A* a;
    /* ect */
};

void Some_Func() {
    B *b;

    // besides this looking ugly, is it legal c++?
    b->a->foo();
};

Is the line b->a->foo() OK to write? Is there a better way to represent this expression?

This is perfectly valid.But the term you are using " pointer to pointer " is wrong.

the term means a double pointer like **P , a pointer which holds the address of another pointer .

but your case is the pointer(of class A) is an member of a class whose pointer(of class B) is created by you in some_func

Illegal, "a" is private. So is "foo".

If corrected to "public" then they're legal constructs.

From your code its hard to find a "better" way. BUT You can modify the code to make the code look much clearer:

class A{
public:
    void foo(){ cout << "Work";}
};

class B{
private:
    A *a;
public:
    A& getA(){
       return *a;
    }
};

void SomeFunction()
{
    B *b = new B();
    B& bRef = *b;
    bRef.getA().foo(); //better looking code? 
        delete b;
}

It is legal but in your example your program will crash (if you could compile it since your members are private) because you did not create an instance of B

void Some_Func() {
    B *b;  // uninitialized B ptr  should be   B* b = new B;

    // legal
    b->a->foo();
};

Although you may want to reconsider accessing variables directly as you do and instead have getter/setters to access private member variables.

Yes but then you have to use pointer to pointer like **P .
Actually if we want to access a pointer which is holding another pointer then we can do this.This is allowed in c++ but keep in mind that only in case if you have assigned a pointer to pointer p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM