Why This doesn't work and the other one works?

This is a discussion on Why This doesn't work and the other one works? within the C++ Programming forums, part of the General Programming Boards category; Hello, i am posting the code. Please tell me why is one of the function defintion working and one is ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    225

    Why This doesn't work and the other one works?

    Hello,
    i am posting the code. Please tell me why is one of the function defintion working and one is not??even though they both look identical!

    i have written the comments also like which one is working and which one is not. Please have a look at them and give me the reason!


    Code:
    #include <iostream.h>
    #include <string.h>
    class student
    {
      char *name,roll[3];
      public:
    	student()
    	{
    		name=new char[20];
    	}
    	student(char *n,char *r)
    	{
    		strcpy(name,n);
    		strcpy(roll,r);
    	}
       friend void sort(student []); //Why This Doesn't Work?
    
       friend void sort(student *); //This Works Perfectly??..
    
    };
    void sort(student a[])         //Why Not Working??
    {
      int j;
      student temp;
      for(int i=0;i<3;i++)
      {
    	for(j=0;j<2;j++)
    	{
    	if(strcmp(a[j].roll,a[j+1].roll)>0)
    		{
    			temp=a[j];
    			a[j]=a[j+1];
    			a[j+1]=temp;
    		}
    	}
      }
    }
    
    
    int main(void)
    {
    
     student a[3];
     a[0]=student("abc","1");
     a[1]=student("def","2");
     a[2]=student("hij","3");
    
     sort(a);
    
     return 0;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Please tell me why is one of the function defintion working and one is not??
    Please define "working" and "not working". The way I see it, your code is not working period, because you don't ever allocate memory to name and then proceed to copy a string to the memory you never allocated. This will likely cause a crash in all cases.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    what exactly are you talking??
    can't you see the memory allocated in default? constructor??and can't you read the //program comments written in function??which says which one is working and which one's not?
    the program is running perfectly. Please dont try to teach me false things i have allocated the memory in constructor. You may see it properly

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    can't you see the memory allocated in default?
    Can't you see that you do not call a default constructor? And call the constructor that does not allocates memory?

    You should learn a little respect before talking in public...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Ok you're right vart
    Sorry Prelude! my tone was not proper

    But what i mean to say is that won't the default constructor be called automatically?i mean it should. Shouldn't it?because i have defined default constructor??then why is it not calling?

    when i create a single object the default constructor is called but when i create array of objects as i created in the above case it's not calling. Why so??

    and also apart from that please tell me why is the friend void sort(student []); not working??in the above example

  6. #6
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    The default constructor is only called if you specify it or if you don't specify any constructor. If you have another constructor and call it, the default constructor is not called behind the scenes. Only the constructor that is called gets executed, in your case the one taking two parameters. And that one is not allocating any memory.

    Concerning your problem, please specify what "Doesn't work" means for you. Does it compile ? Does it link ? Does it produce the desired results ? Where does it fail ? And if it fails to compile or link, what is the error message ?
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  7. #7
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    The error message is "undefined structure result"

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    This line creates 3 students initialised with the default constructor - no problem:
    Code:
     student a[3];
    This line of code constructs another student using only the two-parameter constructor you provided. (That would normally fail, for the reasons stated). Assuming you were very lucky that this happened to not cause an access violation, but instead successfully wrote some garbage over some random memory location instead, it then copy-constructs the newly created student over top of the student at a[0], directly overwriting the value of the name pointer with the uninitialised garbage from the screwed up temporary object, leaking the memory allocated by the default constructor of the original item in a[0].
    Code:
     a[0]=student("abc","1");
    The bug has nothing to do with your sort function implementation or prototype.

    Incidentally, you will be able to do what you wanted I believe, in the next revision of C++ that allows constructor delegation:
    Code:
    	student(char *n, char *r) : student()
    	{
    		strcpy(name,n);
    		strcpy(roll,r);
    	}
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    But i am still not able to understand why will the default constructor not be called automatically??
    if i have defined default constructor shouldn't it be called implicitly at the time of declaring objects itself?
    when i create a single object like --

    student b;
    its calling the default constructor implicitly and when i create array of objects it doesn't call default constructor! Why??what's the reason ?Why not with array of objects?

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,993
    No, it does.

    student a[3];

    Creates 3 student objects, and calls the default constructor for each of them.

    a[0]=student("abc","1");

    Creates a new temporary object student and calls the (char*, int) constructor (not the default one). Then, because they are the same type, the constructor calls the implicit copy constructor which does a shallow copy, that is, copies all of the variables from your temporary student to your a object, hence overwriting your pointer with memory.
    And it's also bad in that the (char*, int) constructor never allocates any memory, so you copy into an uninitialized pointer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Ok now things are getting clear to me!
    But elysia you mean explicit call to constructor always creates a new temporary object?

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,993
    I mean because you are doing
    a[0] = student("abc","1");
    What does this do? It calls the constructor and creates a temporary object, that's all.
    Then it is assigned to the left side, which is another object of the same type.

    You could also do
    student my_student("abc", 1);
    No temporaries because you created a new object named my_student.
    It's called a temporary because its life will not last very long. Once the compiler has assigned it to a[0], it will destruct and get rid of the object. Thus, a temporary.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Ok great!!! elysia good job!
    now i understood! you cleared all my doubts!

    and now the main question. These were all problems pointed to by vart and now other doubt i have is why can't we use sort(student []); in the above example?
    why can i only use only sort(student *);

    These both function declarations mean the same thing. Don't they?then when i call sort(student []); i get a error like undefined structure student
    WHy SO???

  14. #14
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Nobody there to help me out?

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Explain "Not working", as that can cover anything from "not compiling", "sorts in the wrong order" or "crashes when I run the code" - along with probably 100 other things.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21