Bits of Learning

Learning sometimes happens in big jumps, but mostly in little tiny steps. I share my baby steps of learning here, mostly on topics around programming, programming languages, software engineering, and computing in general. But occasionally, even on other disciplines of engineering or even science. I mostly learn through examples and doing. And this place is a logbook of my experiences in learning something. You may find several things interesting here: little cute snippets of (hopefully useful) code, a bit of backing theory, and a lot of gyan on how learning can be so much fun.

Friday, November 30, 2007

Operator overloading

Don't overload the ostream & operator <<. Reason: You can't have this operator as a member function of a class (let me know if I am wrong). Therefore, there doesn't seem to be a way for using polymorphism by declaring these operators as virtual.

#include
#include
#include

using namespace std;

class some
{
protected:
string id;
public:
some (string aid){ id = aid; }
friend ostream & operator (ostream &, some &);
};

ostream & operator << (ostream & fout, some & asome)
{ fout <<
"Class some: " << id << endl;}


class someother : public some
{
public:
someother (string aid) : some (aid){}
friend ostream & operator << (ostream &, someother &);
};

ostream & operator << (ostream & fout, someother & asome)
{ fout <<
"Class someother: " << id << endl;}

int main ()
{
some A ("A");
some
B ("B");
some * C = new
someother ("C");
cout << style="color: rgb(0, 0, 0);">;
cout << B;
cout << (*C);
delete C;
return 0;
}

output:


Class some: A
Class some: B
Class some: C



As you can see above, the objective was to call the operator <<



#include
#include
#include
using namespace std;



class some
{
protected:
string id;
public:
some (string aid){ id = aid; }
friend ostream & operator << (ostream &, some &); virtual ostream &
print (ostream & fout)
{
fout
"Class some: " <<>return fout;
}
};


class someother : public some
{
public:
someother (string aid) : some (aid){}

virtual ostream &
print (ostream & fout)
{
fout <<
"Class someother: " <<>return fout;
}
};


int main ()
{
some
A ("A");
some
B ("B");
some * C = new
someother ("C");
A.
print (cout);
B.
print (cout);
(*C)
print (cout);
delete C;
return
0;
}

No comments: