function Declaration&Definition

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prabu Ramasamy
    New Member
    • Jun 2007
    • 6

    function Declaration&Definition

    As i'm c++ beginner the following Function Declaration and Definition couldnt understandable? so explain me what kind of Declaration this is......?
    especially X& refers what?
    Here instead of datatype X& is used. why?

    Declaration :
    private:

    int len;
    char *ptr;

    public:

    X& Set(char *);


    Definition
    X& X::Set(char *pc)

    {
    len = strlen(pc);
    ptr = new char[len];
    strcpy(ptr, pc);
    return *this;
    }

    Also pleas explain *this without more complex technical terms.
  • OuaisBla
    New Member
    • Jun 2007
    • 18

    #2
    The main thing to know here is about copy constructor and references. Learn that quick if you want to improve your programming skills.

    Example with builtin type (int, float, ...):

    Code:
    int i = 0;
    int j = i;
    
    i = 2;
    ASSERT(j == 0);  //is true
    j is a copy of i at a given time. So changing i doesn't affect j;

    But, if i had a reference on i, thinkgs would have been different:

    Code:
    int i = 0;
    int & j = i;  //here j is a reference on i
    
    i = 2;
    ASSERT(j == 2);  //is true

    This is the same thing for complex object like class or struct. The reasons we use them more on complex object its because that prevent a copy construct called which is totally unefficient.

    Code:
    string s = "a very long and very big string ...";
    
    string s2 = s;  //s2 is a copy so the whole string was copied
    so using function like this:

    Code:
    void f(string s);  
    f(s);  // you have a copy passed as an argument, this is slow
    But:

    Code:
    void f(string const &s);  
    f(s);  // very quick parameters passing. The const is used to tell the compiler that s is supposed to be unmodified in f.
    because:

    Code:
    void f(string &s);  
    f(s);  //quick but my string s could be totally damaged in f!
    So references act like pointers, but they are more elegant and intuitive to use because if you used a reference you do not have to test if it is null or not. Compiler garanty that it can't be null, though it can reference a deleted object, but that's another story.

    Also about "this". this is the pointer on the class object your in. "this" refers to your current object in a given class method. So "*this" means the class object derefenrenced. So you can return yourself either as a copy (slow) or as a reference (quick) either const or not.

    Comment

    Working...