7

i was learning to overload '<<' in a very simple program,& during my study,i found the following surprising output of my program.

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class student
{

int age;

 public:
student(){}
student(int a){age=a;}

friend ostream &operator<<(ostream &stream,student o); 
};

 /*operator overloaded in this block*/
 ostream &operator<<(ostream &stream,student o)
{ 
stream<<o.age;
return stream;
}

int main()
{
student ob1(20),ob2(020);   
cout<<ob1;   /*will yield 20(as desired)*/
cout<<"\n"<<ob2;     /*yielding 16(why so)*/
    _getch();
return 0;
 }

any explainations please

nobalG
  • 4,544
  • 3
  • 34
  • 72
  • 2
    try with 0x20 as well. You'll be surprised. – Tom Aug 11 '11 at 13:52
  • HAHA.....ya i was...bt got the point nw – nobalG Aug 11 '11 at 13:54
  • Pass student by const reference. Otherwise you are making a copy when you pass it into the function. `ostream &operator<<(ostream &stream,student **const&** o)` – Martin York Aug 11 '11 at 13:59
  • Hope you got the answer. For better performance declare it as: `friend ostream &operator<<(ostream &stream,const student& o);` – Ajay Aug 11 '11 at 14:47

6 Answers6

11

0 is the octal prefix for C++ integer literals and 20 in octal is 16 in decimal.

To explain further: If a literal starts with 0 the rest of the number will be interpreted to be in octal representation. In your example 2*8^1 + 0 * 8^0.

The syntax for integer literals is given in §2.14.2 in the most recent standard draft.

pmr
  • 58,701
  • 10
  • 113
  • 156
5
student ob1(20),ob2(020);

You have written 020 which in C and C++ is interpreted as an octal number (base 8) due to the zero at the start. So 020 has the value 16 in decimal.

jcoder
  • 29,554
  • 19
  • 87
  • 130
3

You will find the answer here:

How does C Handle Integer Literals with Leading Zeros, and What About atoi?

You prefixed the literal with a zero, which means treat the number as octal and 20oct is 16dec.

Community
  • 1
  • 1
Skizz
  • 69,698
  • 10
  • 71
  • 108
2

020 is 20 in octal, just as 0x20 is 20 in hex. Remove the preceding 0 and it should work.

user786653
  • 29,780
  • 4
  • 43
  • 53
1

The leading 0 specifies that the it is an octal number (base 8) so 20 in octal is 16.

love_me_some_linux
  • 2,661
  • 1
  • 15
  • 7
1

It's interpereting the 020 as an octal. 2*8=16. Try switching it to a 3, itll show 24 for 030. If you put 0x20 itll go to 32 as its doing hexadecimal. :)

John Humphreys
  • 37,047
  • 37
  • 155
  • 255