Link to home
Create AccountLog in
Avatar of shekhar_shashi
shekhar_shashi

asked on

C++: << Operator does not work as expected

I am trying to overload the << operator.

I have a custom class called person.

I added this to person.h:

public:
.....
....
ostream &person::operator<<(ostream &stream);

I added this to person.cpp
....
....
ostream &person::operator<<(ostream &stream) {
            stream << this->getAge()  << " ";
            return stream;
      }

In the main function, I did the following.
person P4 = person("C", "C", 23); //first name, last name and age
cout << &P4 << " ";

The code compiles fine but when I run the code, I see this output:
0012FDFC

I am expecting output:
23

I am using Visual Studio 2008.

Not sure what am I doing wrong. Please help. Thanks in advance.
SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of shekhar_shashi
shekhar_shashi

ASKER

If I change the code this way, I get this compilation error:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'person' (or there is no acceptable conversion)      
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Pardon my C++ ignorance here.

I am getting about 9 compilation errors after making these code changes.

Instead of posting all the compilation errors, let me ask a few questions:

Question 1:
Where should the forward declaration go?

class person; // foward declaration

ostream& operator<< ( ostream& os, const student& p) ;

Question 2: I am guessing this code needs to be placed in the header file.

class person
{
  friend ostream& operator<< ( ostream& os, const person& p) ;

  // ...

};

Am I correct?

Question 3:

I am guessing this code will be placed in the person.cpp file.

ostream& operator<< ( ostream& os, const person& p)
{
  os << p.getAge();

  return 0s;
}
 
Am I correct?

Thanks.


SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Your answer was spot on.  Thanks a bunch for helping out this C++ newbie.
Thanks