Find the answer to your Linux question:
Results 1 to 2 of 2
In one of my project I am going through some code. I need some help on this. Code Snipnet: class B{}; class A{ public: void method1(B* b){ b = new ...
  1. #1
    Just Joined!
    Join Date
    Jan 2011
    Posts
    1

    C++ object creating

    In one of my project I am going through some code. I need some help on this.

    Code Snipnet:

    class B{};
    class A{
    public:
    void method1(B* b){
    b = new B();
    }
    void method2(B*& b) {
    b = new B();
    }
    };
    int main(void){
    A a;
    B* b = new B;
    a.method1(b);
    a.method2(b);
    }

    What is the difference between method1 and method2

    Thanks in advance
    Madhu

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    This sounds a bit like a homework problem, which are not allowed on these forums.

    However, I'll give you a bit of advice (and if it's not a homework problem, please let us know).

    The difference lies in the '&' in the parameter list. For simplicity's sake, assume that the parameters are not pointers; assume, for instance, that the actual code is:
    Code:
    void method1(string s){
        s = "foo";
    }
    void method2(string &s) {
        s = "foo";
    }
    This is a technique called pass-by-reference, where modifying a parameter modifies the parameter that was used to call the function.

    There are a number of resources online that explain this well.
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...