473,592 Members | 2,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Polymorphism - run-time vs. compile-time

Hello,
The other day I was rather shocked to find that I couldn't find
a good use for runtime polymorphism! Let me explain this a bit further
before you get shocked. Any function that I could previously write like
this:
void func1(Base& obj)
{
//...
obj.virmeth(); //Call virtual method
//...
}

Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}

That way, I'll never incurr run-time overheads. Obviously, this
wouldn't
work if I'm trying to separate implementation from use, but this
question hit me so suddenly, that I really couldn't find a good answer
then. Now I figured out two situations where this isn't possible: when
return type must be polymorphic (or is that also used in automatic
template specialization? ) ... or when catching exceptions. But I'd
still like to shake myself off this uneasy feeling by hearing a bit
more over which is more suitable when - and even in the cases I
mentioned, I'd like a little discussionW (exceptional cases etc.)

Samee

Jul 23 '05 #1
7 5378
Samee Zahur wrote:
Hello,
The other day I was rather shocked to find that I couldn't find
a good use for runtime polymorphism!
That would shock me too ;-)
Let me explain this a bit further before you get shocked. Any function
that I could previously write like this:
void func1(Base& obj)
{
//...
obj.virmeth(); //Call virtual method
//...
}

Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}

That way, I'll never incurr run-time overheads. Obviously, this
wouldn't work if I'm trying to separate implementation from use, but this
question hit me so suddenly, that I really couldn't find a good answer
then. Now I figured out two situations where this isn't possible: when
return type must be polymorphic (or is that also used in automatic
template specialization? ) ... or when catching exceptions. But I'd
still like to shake myself off this uneasy feeling by hearing a bit
more over which is more suitable when - and even in the cases I
mentioned, I'd like a little discussionW (exceptional cases etc.)


What if the actual type of the object is not determined at compile time, but
at runtime? Think of one classic example - a drawing program. The user can
draw circles, rectangles, text, whatever. When painting the objects on the
screen, the program goes through the list of objects and renders them all.
How does the program know at compile time, which paint function to call for
each of the objects?

Jul 23 '05 #2
Samee Zahur wrote:

Hello,
The other day I was rather shocked to find that I couldn't find
a good use for runtime polymorphism! Let me explain this a bit further
before you get shocked. Any function that I could previously write like
this:
void func1(Base& obj)
{
//...
obj.virmeth(); //Call virtual method
//...
}

Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}


That's not better.
The important part in polymorphism is exactly that: You don't
know the runtime type T during compile time. Well, if you
don't know it, how should the compiler know when it instantiates
the template?

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #3
To everyone, thanks ...
Even these textbook examples did unclog my mind quite a bit.

Samee

Jul 23 '05 #4
Karl Heinz Buchegger wrote:
Samee Zahur wrote:
Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}

That's not better.
The important part in polymorphism is exactly that: You don't
know the runtime type T during compile time. Well, if you
don't know it, how should the compiler know when it instantiates
the template?


You don't know it?
You mean - when you do:

int main () {
std::vector<std ::string> test = "woop";
std::string * p2test = test;
func1(test);
return 0;
}

You DON'T know test?
Now, I personally think polymorphism is to generalize the function so
you don't have to write out several different versions of the same
function for different data types.

Please, explain..
And that code, I make no claims it is compilable - nor 100% correct....
I don't like pointers much.

--
Tr0n˛
--
Jul 23 '05 #5
Tr0n˛ wrote:
That's not better.
The important part in polymorphism is exactly that: You don't
know the runtime type T during compile time. Well, if you
don't know it, how should the compiler know when it instantiates
the template?

You don't know it?
You mean - when you do:

int main () {
std::vector<std ::string> test = "woop";
std::string * p2test = test;
func1(test);
return 0;
}

You DON'T know test?


The OP was talking about polymorphism.
The above has nothing to do with polymorphism, the above is
simply a pointer to an object.
Now, I personally think polymorphism is to generalize the function so
you don't have to write out several different versions of the same
function for different data types.


You obviously haven't understood what polymorphism is for and
what problem it solves.

Eg.

class Animal
{
public:
virtual void MakeNoise() {}
};

class Cat : public Animal
{
public:
virtual void MakeNoise() { std::cout << "Miau\n"; }
};

class Dog : public Animal
{
public:
virtual void MakeNoise() { std::cout << "Wuff\n"; }
};

void foo( Animal* pAnimal )
{
pAnimal->MakeNoise(); // here is the polymorphic call
// does pAnimal point to a Cat
// or a Dog? Nobody knows at this
// place. But it doesn't matter.
// Thanks to polymorphism the correct
// MakeNoise() function for Cats and/or Dogs
// is called.
}

int main()
{
Animal* Pets[2];

Pets[0] = new Cat;
Pets[1] = new Dog;

foo( Pets[0] );
foo( Pets[1] );

delete Pets[0];
delete Pets[1];
}

I invite you now to find a way to rewrite MakeNoise and foo
using templates without altering main() such that the program
behaves the very same.

Good luck!

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #6
Tr0n² wrote:
Karl Heinz Buchegger wrote:
Samee Zahur wrote:
Is now better written as this for most cases:
template <class T> void func1(T& obj)
{
//...
obj.virmeth(); //Call any method
//...
}
That's not better.
The important part in polymorphism is exactly that: You don't
know the runtime type T during compile time. Well, if you
don't know it, how should the compiler know when it instantiates
the template?


You don't know it?
You mean - when you do:

int main () {
std::vector<std ::string> test = "woop";
std::string * p2test = test;
func1(test);
return 0;
}

You DON'T know test?


You do know it. But this is not an example for polymorphism.
Just let's try another example, where polymorphism is actually used:

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

class Base
{
public:
virtual void do_something() = 0;
virtual ~Base() {}
};

class Derived1 : public Base
{
public:
virtual void do_something()
{
std::cout << "We're Derived1\n";
}

virtual ~Derived1()
{
std::cout << "Destroyed a Derived1\n";
}
};

class Derived2 : public Base
{
public:
virtual void do_something()
{
std::cout << "Now this is a Derived2\n";
}

virtual ~Derived2()
{
std::cout << "Oh no, I'm such a young Derived2, don't kill me\n";
}
};

int main()
{
std::vector<Bas e*> vec;
std::cout << "Instance of which type to add?";
std::string name;

for(;;)
{
std::cin >> name;

if (name == "end")
break;

if (name == "Derived1")
vec.push_back(n ew Derived1);
else
vec.push_back(n ew Derived2);
}

for (int i = 0; i < vec.size(); ++i)
vec[i]->do_something() ;

for (int i = 0; i < vec.size(); ++i)
delete vec[i];
}

Now, please rewrite that to use templates instead of virtual functions.
Now, I personally think polymorphism is to generalize the function so
you don't have to write out several different versions of the same
function for different data types.


No, it's not. That's what templates are for.

Jul 23 '05 #7
Rolf Magnus wrote:
Tr0n² wrote: <snip>
Now, please rewrite that to use templates instead of virtual functions.

Now, I personally think polymorphism is to generalize the function so
you don't have to write out several different versions of the same
function for different data types.

No, it's not. That's what templates are for.


Ahhh - thank you very much, Karl and Rolf.
I also say thank you for not taking it the wrong way, and simply
pointing at me and laughing instead of throwing the proverbial stick!

I half understand now... It's to do with objects with virtual functions
- the actions of which can change depending on the object.

And yes, I'm at the start of my journey down the yellow brick road - but
I'm sure not going to stop at the first crack.

Thanks for your assistance.

--
Tr0n˛
--
Jul 23 '05 #8

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

Similar topics

3
2130
by: Mayer Goldberg | last post by:
Can someone please explain the motivation behind the following restriction in the language: I define an interface and two classes implementing it: public interface InterA {} public class B implements InterA {} public class C implements InterA {}
7
4538
by: rashkatsa | last post by:
Hi all ! I have written a little module called 'polymorph' that allows to call different methods of a class that have the same name but that have not the same number of arguments. *args are supported. You could find the module attached to this message. As in python, you could not define two method with same name (the second one override the first one), i have choosen to design it through private prefix '__' (defined method names and...
37
2813
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic typing language? I searched and found several different ways to do this:
10
5205
by: Danny Ni | last post by:
Hi, I was asked a question in a recent interview, where in ASP.Net is polymorphism used? I got differrent answers from different people, One said ToString() method because it is working for different classes. One said OnInit() method of System.Web.UI.Page class because it's defined virtual and that's the key to polymorphism.
35
2185
by: JKop | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en- us/vccore98/HTML/_core_using_strict_type_checking.asp Pay particular attention to: The types WPARAM, LPARAM, LRESULT, and void * are “polymorphic data types.” ....when is Microsoft gonna cop-on?
5
1296
by: Steven T. Hatton | last post by:
I've run into a situation where the conventional thinking doesn't seem satisfactory. I have a table of data where each row maps into a struct. I want to put these into a vector. My overall design uses interfaces for everything accessed from outside of the namespace. I also have a class that acts as a wrapper for the structs. For example: struct Row { long _col0; long _col1; }; class TableRow_IF { public:
4
7387
by: LP | last post by:
Hi, I understand the concept/definition of polymorphism. But what does the term "runtime polymorphism" mean? I was asked to define it during a technical interview. I gave a guy vanilla definition of polymorphism, but he insisted on runtime. Did I miss a new buzzword while I was sick with the flu last week or something like that?
2
735
by: glen stark | last post by:
I have a templated function template<class T> void update_E(T& updateable) { .... } What I would like to do is store a vector of updateable objects, and for each of them call the update function. What and how many updateable objects area actually created is determined at runtime.
13
14602
by: Krivenok Dmitry | last post by:
Hello all! Perhaps the most important feature of dynamic polymorphism is ability to handle heterogeneous collections of objects. ("C++ Templates: The Complete Guide" by David Vandevoorde and Nicolai M. Josuttis. Chapter 14.) How to implement analogue of this technique via static polymorphism? Perhaps there is special design pattern for this purpose...
11
2958
by: chsalvia | last post by:
I've been programming in C++ for a little over 2 years, and I still find myself wondering when I should use polymorphism. Some people claim that polymorphism is such an integral part of C++, that anybody who doesn't use it might as well just program in plain C. I totally disagree with this, because I think C++ has a lot of great features apart from polymorphism, such as the ability to organize code into classes, code reuse through...
0
7935
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
7871
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
8366
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
7995
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,...
1
5735
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
3851
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...
1
2379
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
1
1467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1202
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.