473,734 Members | 2,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

polymorphic return types in virtual functions

If I have something like this:

class NumberException {
};

class Number {
public:
...
virtual unsigned long getValue() {throw(NumberEx ception);};
...
};

class Integer : public Number {
public:
...
virtual int getValue() {return Value;};

Integer(int i) {Value=i;};
...

private:
int Value;
};

class Float : public Number {
public:
....
virtual float getValue() {return Value};

Float(float f);
....

private:
float Value;
};

int main()
{
Float f(3.14);
Integer i(55);

cout<<f->getValue()<< " "<<i->getValue()<<en dl;
}

GCC (and likelly any other ANSI compilor) barfs on getValue having different
return types while being virtual... is there any way around this problem...
the idea is I want to do a "everything is an object" style paradigm (ala
Ruby).

--Aryeh
Jul 23 '05 #1
2 3892
On 2005-02-20, Aryeh M. Friedman <ar***@m-net.arbornet.or g> wrote:
If I have something like this:

class Number {
public:
virtual unsigned long getValue() {throw(NumberEx ception);};
};

class Integer : public Number {
public:
virtual int getValue() {return Value;}; class Float : public Number {
public:
virtual float getValue() {return Value};
Not clear on what the above is trying to achieve .. but hopefully this will
help:

Here's the problem -- consider this:

Number* x = new Integer(0);
x->getValue(); // what type does this return ?

Everything needs to return a certain type.

If you want a function to return multiple types, you need to hide the type
behind a dynamic pointer, e.g.

// always returns Number*, but the underlying object could be an Integer or
// Float
Number* f(int i, bool j) {
if (j)
return new Float(i);
else
return new Integer(i);
}
int main()
{
Float f(3.14);
Integer i(55);

cout<<f->getValue()<< " "<<i->getValue()<<en dl;


This is incorrect code. The correct way to write this would be something like

int main()
{
Number* f = new Float(3.14);
Number* i = new Integer(55);
std::cout << *f << " " << *i << std::endl;
}

Then you need to overload operator<<.

e.g.

class Number {
public:
virtual std::string tostring = 0;
};

std::ostream& operator<< ( std::ostream& s, const Number& n) {
s << n.tostring();
}

Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/
Jul 23 '05 #2
Aryeh M. Friedman wrote:

GCC (and likelly any other ANSI compilor) barfs on getValue having different
return types while being virtual... is there any way around this problem...
the idea is I want to do a "everything is an object" style paradigm (ala
Ruby).

You can only have covariant return types from virtual functions when one
is a base class of the other. It's more specific than just being "convertabl e"
to the other.

The numerical types in C++ are not polymorphic. You could do it like this:

class Number {
unsigned long GetValue() { return getValueUL(); } // Not virtual.
virtual unsigned long GetValueUL() { return Value; }
};

class Float {
float GetValue() { return Value; }
unsigned long GetValueUL() { return Value(); } // definite covnersion.
};
Jul 23 '05 #3

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

Similar topics

20
2223
by: verec | last post by:
One problem I've come accross in designing a specific version of auto_ptr is that I have to disntiguish between "polymorphic" arguments and "plain" ones, because the template has to, internally, cast to void *. Specifically, template <typename T> void f(T * t) { void * p = dynamic_cast<void *>(t) ; } will not compile if T isn't of a class that has somewhere at least
1
2258
by: verec | last post by:
Last week I asked here how I could detect that a T was polymorphic, and received very thoughtful and useful replies that I used straight away. Thanks to all who answered. This week, it turns out that detecting whether T is polymorphic clashes with a new requirement, that T be allowed to not be complete. Last week, this code used to compile:
9
2128
by: Karel Miklav | last post by:
In lots of places in a programm I need to identify type of received messages, so I create them as virtual classes and use RTTI to find their type later. But these are simple messages, often without content, and I hate how I make their base class: by adding a dummy virtual function. Is there another way? -- Regards,
23
2518
by: Randy | last post by:
Since these operators can't be member functions, and since friend functions can't be declared virtual, how do I make my inserters and extractors polymorphic? --Randy Yates
5
2780
by: FefeOxy | last post by:
Hi, > I'm having a debug assertion error within the file dbgdel.cpp with the expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) I traced the origin of the error and it happened as I tried to delete a polymorphic class as follows:
5
3418
by: Ben Pope | last post by:
Hi all, This is not something I've played around with much, but I'm designing some factories and I want a function like this: template<class T> T* Creator() { return new T; }
4
1704
by: Osamede.Zhang | last post by:
Compiler store a pointer table in each object with virtual fuction to implement polymorphic,isn't it? But where is the pointer table? It seems that object only store a pointer to the table,the output of this code is 88. #include<iostream> using namespace std; class MyClass{ public: MyClass(){ a=0;} virtual void tst1() {a-=1;}
3
3910
by: jacek.dziedzic | last post by:
Hello! Suppose I have a class base, with virtual methods and a virtual destructor and a bunch of classes, derived1, derived2, ... which publicly derive from base. I then have a pointer base* foo; which a complicated code allocates as one of derived's and sets up.
11
1481
by: Angus | last post by:
I am developing a server which receives a range of different messages. There are about 12 different message types so I thought that a good idea would be to devise a class for each message type. Then in my base class I for example have a pure virtual function called eg PerformAction. Then in each message class I implement PerformAction. The base class works out what the type of message is and then calls the correct inherited class...
0
8951
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8783
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
9458
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...
0
9317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9248
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
8192
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...
0
6040
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4555
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.