By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,650 Members | 1,785 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,650 IT Pros & Developers. It's quick & easy.

why this behavious abnormal ?

P: 9
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. class A
  7. {
  8. private:
  9. int a;
  10. int b;
  11.  
  12. public:
  13.  
  14.  
  15.  
  16. A( int i, int j) : a(i), b(j)
  17.  
  18. {
  19. cout << "intitialize a = " << a << endl;
  20. cout << "intitialize b = " << b << endl;
  21.  
  22. }
  23.  
  24.  
  25.  
  26. friend ostream& operator<<(ostream &os, const A &obj)
  27.  
  28. {
  29.  
  30. os << obj.a << obj.b ;
  31.  
  32. return os; // if i forget to return this referance.....
  33.  
  34. }
  35.  
  36. };
  37.  
  38.  
  39.  
  40. int main()
  41.  
  42. {
  43.  
  44.  
  45. A *aobj = new A(5,10);
  46.  
  47. cout<< aobj;
  48.  
  49. cout<<endl;
  50.  
  51.  
  52.  
  53. return 0;
  54.  
  55. }
  56.  
code as shown above...

i am getting :

my o/p : 004800f0

but expected is 510

why ? // i used vc6 IDE
Jun 15 '07 #1
Share this Question
Share on Google+
2 Replies


P: 9
#include <iostream>

using namespace std;


class A
{
private:
int a;
int b;

public:



A( int i, int j) : a(i), b(j)

{
cout << "intitialize a = " << a << endl;
cout << "intitialize b = " << b << endl;

}



friend ostream& operator<<(ostream &os, const A &obj)

{

os << obj.a << obj.b ;

return os; // if i forget to return this referance.....

}

};



int main()

{


A *aobj = new A(5,10);

cout<< aobj;

cout<<endl;



return 0;

}

code as shown above...

i am getting :

my o/p : 004800f0

but expected is 510

why ? // i used vc6 IDE
i had fixed this problem.....


in two ways...

1. object from stack...


A aobj(5,10);

cout<< aobj;

2. object from heap...

A *aobj = new A(5,10);

cout<< *aobj;

both o/p will be 5 10
Jun 15 '07 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
I'm glad you fixed it.

This is a common error:
Expand|Select|Wrap|Line Numbers
  1. A *aobj = new A(5,10);
  2.  
  3. cout<< aobj;
  4.  
The address of aobj is displayed. So your fix is correct:

Expand|Select|Wrap|Line Numbers
  1. cout << *aobj;
  2.  
It's a little different with the stack object since stack object's address is &aobj. Therefore, cout << aobj will work. To se the address of the stack objct oyuwould need to cout << &aobj.
Jun 15 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.