(C++) Not sure what the problem wants me to do.

  • Context: Comp Sci 
  • Thread starter Thread starter cpponyou
  • Start date Start date
Click For Summary
SUMMARY

The discussion centers on implementing an overloaded operator<< for a class hierarchy in C++. The task requires creating a function that allows the output of class members through the standard output stream using the syntax out << p, where p is an object of the class. The solution involves ensuring that the overloaded operator adheres to the semantics of the existing stream operators, enabling chaining of output statements.

PREREQUISITES
  • Understanding of C++ class hierarchies
  • Familiarity with virtual functions in C++
  • Knowledge of operator overloading in C++
  • Experience with output streams in C++ (ostream)
NEXT STEPS
  • Study C++ operator overloading techniques
  • Learn about virtual functions and polymorphism in C++
  • Explore the implementation of ostream and its usage
  • Investigate best practices for designing class interfaces in C++
USEFUL FOR

C++ developers, software engineers, and students learning object-oriented programming who seek to enhance their understanding of operator overloading and class design principles.

cpponyou
Messages
1
Reaction score
0
I have this HW problem, but I cannot figure out what it wants me to do. I don't want anyone to solve it for me, just point me in the right direction.

Suppose that a class hierarchy has a virtual method print
Code:
class C {
virtual void print( ostream& ) const;
};

that outputs C's members to the stream ostream. Write one overload of << so that the statement

Code:
out << p;

outputs p's members to the stream out, where p is any object that belongs to a class in the hierarchy.

What I don't understand is the out << p bit. Am I supposed to be able to do

Code:
out << p;

in my main() and have the overload call p.print() ?
 
Physics news on Phys.org
That is exactly what you are supposed to do.

You should probably make your overloaded function obey the semantics of the << operator as used with streams so that given two such objects p and q the following works:
Code:
out << "Members of p:\n" << p << "\nMembers of q:\n" << q;
 
Last edited:
Indeed. So they want you to override operator<<
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K