473,881 Members | 1,517 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with results of overloading << for polymorphic types...

Hi all,

I'm having a problem and for illustration purposes I developed code
that shows what the problem is about. However, any comment on the code
which is not directly about this issue is surely welcome. I have 3
classes, A is abstract, B and C inherit from A and then I create a
vector with B's and C's and print them. Of course, I overload << for
each one of them.
So it is as follows:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A {
public:
A(string n) : name(n) {}
virtual ~A() {}

virtual string getName() = 0;

protected:
string name;

private:
friend
ostream& operator<<(ostr eam& s, A& val) {
return s << "<UNPRINTABLE_A >";
}
};

class B : public A {
public:
B(string n) : A(n) {}
virtual ~B() {}

virtual string getName();

private:
friend
ostream& operator<<(ostr eam& s, B& val) {
return s << "Class B: " << val.getName();
}

};

string B::getName() {
string s = "My name is " + name + ".";
return s;
}

class C : public A {
public:
C(string n) : A(n) {}
virtual ~C() {}

virtual string getName();

private:
friend
ostream& operator<<(ostr eam& s, C& val) {
return s << "Class C : " << val.getName();
}
};

string C::getName() {
string s = name + "is my name.";
return s;
}

int main() {

vector<A*> v;
v.push_back(new B("b1"));
v.push_back(new B("b2"));
v.push_back(new C("c1"));
v.push_back(new B("b3"));

for(vector<A*>: :iterator i = v.begin(); i != v.end(); i++)
cout << **i << endl;

return 0;

}

When I run the program I get:
$ ./testop
<UNPRINTABLE_ A>
<UNPRINTABLE_ A>
<UNPRINTABLE_ A>
<UNPRINTABLE_ A>

This is surely not what I expected. How can I have the << for B and C
called?
It's idiot to even have <UNPRINTABLE_ A> printed. It should never be
printed. Initially I didn't even though that I needed to overload <<
for A but I do because **i is an A and I do not know if it is a B or a
C. It's logic but at the same time confusing!

Cheers,

Paulo Matos

Jul 23 '05 #1
3 1331
"pmatos" <po**@sat.ine sc-id.pt> wrote...
I'm having a problem and for illustration purposes I developed code
that shows what the problem is about. However, any comment on the code
which is not directly about this issue is surely welcome. I have 3
classes, A is abstract, B and C inherit from A and then I create a
vector with B's and C's and print them. Of course, I overload << for
each one of them.
So it is as follows:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A {
public:
A(string n) : name(n) {}
virtual ~A() {}

virtual string getName() = 0;

protected:
string name;

private:
friend
ostream& operator<<(ostr eam& s, A& val) {
return s << "<UNPRINTABLE_A >";
Do

return val.print(s);
}
Add

ostream& print(ostream&) = 0;
};

class B : public A {
public:
B(string n) : A(n) {}
virtual ~B() {}

virtual string getName();

private:
friend
ostream& operator<<(ostr eam& s, B& val) {
return s << "Class B: " << val.getName();
}
Drop that and implement the 'print' member function instead.

};
[...]


V
Jul 23 '05 #2
pmatos wrote:
Hi all,

I'm having a problem and for illustration purposes I developed code
that shows what the problem is about. However, any comment on the
code which is not directly about this issue is surely welcome. I
have 3 classes, A is abstract, B and C inherit from A and then I
create a vector with B's and C's and print them. Of course, I
overload << for each one of them.


Create a (possibly pure) virtual function in the base class to print it
self out. Create an operator<< that calls that virtual function to do
the job. Override the virtual function in the derived classes as
needed. Make sure your operator<< receives the object by const
reference so polymorphism will work.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #3
"Victor Bazarov" <v.********@com Acast.net> wrote...
"pmatos" <po**@sat.ine sc-id.pt> wrote...
[..]
Do

return val.print(s);
}
Add

ostream& print(ostream&) = 0;


Did I miss the 'virtual' keyword here? Damn! Should be

virtual ostream& print(ostream&) = 0;
[..]

Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
3107
by: Philipp Lenssen | last post by:
My friend has the following problem (background: we want to transform XML to XHTML via XSLT): "We copy XHTML fragments into an output by using the following template: <xsl:template match="*" mode="xhtml"> <xsl:element name="{local-name()}"> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="xhtml"/> </xsl:element>
10
1674
by: pmatos | last post by:
Hi all, I have the following code: class test { public: test(const std::string *n) : name(n) {} virtual ~test() {} const std::string * getName() { return name; }
2
1318
by: zeroYouMustNotSpamtype | last post by:
Hi, Describing this problem will be a bit long winded, but please bear with me: I've got three files in my project: permuts.h, permuts.cpp, and braids.cpp (some content from wich will eventually be moved into braids.h). Both cpp files include the h file. Permuts.h contains the Permutation class, for which I needed to overload <<. Doing this in that file caused an error(Duplicate definition I think - it occurs to
3
1664
by: Suresh Tri | last post by:
Hi all, I was trying to overload '<' operator for (varchar,varchar). But in the function which handles the comparision I want to use the previous '<' operator.. but it is going into a recursion. My simplified code looks like : create or replace function orastringcmp (varchar, varchar) returns boolean as 'declare
13
1665
by: guitarromantic | last post by:
Hey everyone. I'm editing some stuff I did last summer, trying to bugfix and improve stuff. One improvement (or an oversight of the original design) is adding dynamic <title> tags to my pages. Here's how I originally structured my php pages: include header.php (contents are basically my HTML/CSS up to the <!--begin content--> point) <php code>
3
1738
by: johnmmcparland | last post by:
Hi all, I know it is possible to overload the operators and < in C++ but how can I do this. Assume I have a class Date with three int members, m_day, m_month and m_year. In the .cpp files I have defined the < and operators; bool Date::operator<(const Date& d) {
10
1826
by: ozizus | last post by:
I overloaded operator << for STL map successfully: template <typename T1, typename T2ostream & operator << (ostream & o, map <T1,T2& m) { //code } the code works like a charm. Now, I want the same functionality for multimap. Since their interface is same for the problem at hand, I
8
1731
by: Micko1 | last post by:
hi there, I have an issue when overloading <<. string operator << (room * &currentPlayerLocation); string room::operator << (room * &currentPlayerLocation) {
1
4971
by: ghjk | last post by:
In my php page there is a search function and when user search it will display table containing search results. I want to add <a href ..></a> . Because when user click one record I want to pass values to ajax page. to those results. But my code is not working. Please help me.This is my code. while($row = mysql_fetch_array($result)) { echo "<a href='javascript:void(0);'...
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11096
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10812
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10400
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9552
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7953
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.