different result <c++builder, gcc, msvc++10

#include <iostream>
#include <cstdlib>
using namespace std;
class myclass
{
int *p;
public:
myclass(int i);
myclass(const myclass &i);
~myclass() { system("pause"); delete p; }
friend int getval(myclass o);
};

myclass::myclass(const myclass &i)
{
p=new int;
if(!p) exit(1);
*p=*i.p;
}
myclass::myclass(int i=0)
{
p=new int;
if(!p) exit(1);
*p=i;
}

int getval(myclass o)
{
return *o.p;
}

int main()
{
myclass a,b,c;

a=b;
b=c;
c=a;

cout<<getval(a)<<endl;

return 0;
}

guys tell why does the above code have different result in different compiler:
gnu c++, c++builder, ms visual c++ 2010
#include <iostream>
#include <cstdlib>
using namespace std;
class myclass
{
int *p;
public:
myclass(int i);
myclass(const myclass &i);
~myclass() { system("pause"); delete p; }
friend int getval(myclass o);
};

myclass::myclass(const myclass &i)
{
p=new int;
if(!p) exit(1);
*p=*i.p;
}
myclass::myclass(int i=0)
{
p=new int;
if(!p) exit(1);
*p=i;
}

int getval(myclass o)
{
return *o.p;
}

int main()
{
myclass a,b,c;

a=b;
b=c;
c=a;

cout<<getval(a)<<endl;

return 0;
}

guys please tell me why does the above code have different result in different compiler:
gnu c++, c++builder, ms visual c++ 2010
Last edited on
closed account (DSLq5Di1)
The copy constructor is only being called once in this program.. and probably unintentionally?
http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html

The default value in your constructor definition may cause some confusion too, I'd recommend moving it into your class declaration.
uhmm...ok, but when i move it to class block itll make it inline which only touch the surface of memory i dynamically allocated.
myclass operator=(myclass &o) { *p=*o.p; return *this; } --this eliminates the problem but still

the three compiler have different result...please explain it to me?
What do you mean with "different result"? does it behave differently, or is something else different (like the exectuable size)? The standard guarantees that the same statements lead to the same behavior defined by the standard - it doesn't say how exactly the compiler has to accomplish this.
closed account (DSLq5Di1)
Without overloading the assignment operator, this is what you are doing:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int *a, *b, *c;

a = new int(0);
b = new int(0);
c = new int(0);

a = b;
b = c;
c = a;

// a and c point to the same location, the memory originally allocated for a is lost.

delete a;
delete b;
delete c; // bigbadaboom 

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.2
@hanst99

yes it behave differently... the two compiler issued no error it runs fine but the other one it compiled and run but it has a different result.
may the error is in my system ill try re installing my os...coz last time i had this experience three compilers have different result, but that was unary operation..
Topic archived. No new replies allowed.