Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

Passing an address to a class and from there to its "child-class" by reference in C++

"pointer" holds the address of "Int". I want to pass that address to my given classes by reference:

class N {
public:
    N(int &pPointer){   
        std::cout << "Address: " << &(pPointer) <<" 
";
    }
};
class M {
public:
    M(int &pPointer):n(pPointer) {              
       std::cout << "Address: " << &pPointer <<" 
";
    }   
    private:
     N n;
};

int main () {
    int Int = 5;
    int *pointer = &Int;    
    std::cout << "Address: " << pointer <<" 
";
    M m(*pointer);  
     return 0;
}

Is this a good practice (since I'm kind of using a reference to a dereferenced pointer)? Or is it absolutely horrible? I simply want to avoid pointers here. (Although I'm forced to use "*pointer" in the beginning. )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's totally OK to pass by reference instead of passing by pointer to use the abject later, as lon you know the pointer you are using is valid. This allows you to skip the nullptr check, because references can't be null.
However if you store a reference, you won't be able to replace the object being referred to, to another. But you can do that with a pointer.
You can, later, take the address of the referenced object, but do you really think you need to do that? Because you can use the reference instead


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...