Logo 
Search:

C++ Programming FAQ

Submit Interview FAQ
Home » Interview FAQ » C++ ProgrammingRSS Feeds

C++ programming practical question 9

  Shared By: Adah Miller    Date: Jan 24    Category: C++ Programming    Views: 77

Answer:

#include <iostream.h>

class fig2d
{
int dim1;
int dim2;

public:
fig2d() { dim1=5; dim2=6;}

virtual void operator<<(ostream & rhs);
};

void fig2d::operator<<(ostream &rhs)
{
rhs <<this->dim1<<" "<<this->dim2<<" ";
}

/*class fig3d : public fig2d
{
int dim3;
public:
fig3d() { dim3=7;}
virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
fig2d::operator <<(rhs);
rhs<<this->dim3;
}
*/

void main()
{
fig2d obj1;
// fig3d obj2;

obj1 << cout;
// obj2 << cout;
}


Answer :
5 6


Explanation:
In this program, the << operator is overloaded with ostream as argument.
This enables the 'cout' to be present at the right-hand-side. Normally, 'cout'
is implemented as global function, but it doesn't mean that 'cout' is not possible
to be overloaded as member function.
Overloading << as virtual member function becomes handy when the class in which
it is overloaded is inherited, and this becomes available to be overrided. This is as opposed
to global friend functions, where friend's are not inherited.

Share: 
 

Didn't find what you were looking for? Find more on C++ programming practical question 9 Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: