Hello. I'll try to explain my problem with an example:
I have the following classes:
class A {
public:
string name;
....
};
class B : public A
{
B(int x) {b=x; name="I am B"; }
int b;
getB() { return b };
};
class C : public A
{
C(int x) {c=x; name="I am C"; }
int c;
getC() { return c; }
};
Now, I need a vector<A*> v;
An there is a function like the following:
void p()
{
...
if(v[i]->name=="I am B"){ v[i]->getB() ...};
...
if(v[j]->name=="I am C") { v[j]->getC() ... };
...
};
It doesn't work because v contains objects of class A, but A doesn't
implement getB() nor getC().
But I need to have in the same vector objets of A, B and C. And I don't want
to declare getB and getC as virtual in A, because these methods will only be
defined in classes B and C respectively.
How can I do that?
Thanks. 25 1727
Some corrections: I have the following classes:
class A { public: string name; ... };
class B : public A { int b;
public:
B(int x) {b=x; name="I am B"; } getB() { return b }; };
class C : public A { int c;
public:
C(int x) {c=x; name="I am C"; }
getC() { return c; } };
Now, I need a vector<A*> v;
An there is a function like the following:
void p() { ... if(v[i]->name=="I am B"){ v[i]->getB() ...}; ... if(v[j]->name=="I am C") { v[j]->getC() ... }; ... };
It doesn't work because v contains objects of class A, but A doesn't implement getB() nor getC(). But I need to have in the same vector objets of A, B and C. And I don't want to declare getB and getC as virtual in A, because these methods will only be defined in classes B and C respectively.
How can I do that?
Thanks.
Nafai wrote: Some corrections:
More corrections
I have the following classes:
#include <string>
using std::string;
class A { public: string name; ... };
class B : public A { int b; public: B(int x) {b=x; name="I am B"; }
getB() { return b };
int getB() { return b };
};
class C : public A { int c;
public: C(int x) {c=x; name="I am C"; } getC() { return c; }
int getC() { return c; } };
Now, I need a vector<A*> v;
An there is a function like the following:
void p() { ... if(v[i]->name=="I am B"){ v[i]->getB() ...}; ... if(v[j]->name=="I am C") { v[j]->getC() ... }; ... };
It doesn't work because v contains objects of class A,
Actually, v contains _pointers_ to objects of class A. It would be
a disaster if v contained _objects_.
but A doesn't implement getB() nor getC(). But I need to have in the same vector objets of A, B and C. And I don't want to declare getB and getC as virtual in A, because these methods will only be defined in classes B and C respectively.
How can I do that?
Declare
virtual int getValue() = 0;
in A and make B and C implement it by calling getB and getC respectively.
V Declare
virtual int getValue() = 0;
in A and make B and C implement it by calling getB and getC respectively.
V
what about if C is like this (A and B are like before):
class C {
int c1, c2;
public:
int getC1() { return c1; }
int getC2() { return c2; }
};
vector<A*> v;
void p()
{
....
v[i]->getC1();
...
v[i]->getC2();
...
}
And another question:
list<A*> l;
A* p = new C(...);
l.push_front(p) ;
l.pop_front();
is *p destroyed?
Or even more: will list<A*>'s destructor destroy all the elements of l ?
Alexandros wrote: Declare
virtual int getValue() = 0;
in A and make B and C implement it by calling getB and getC respectively.
V
what about if C is like this (A and B are like before):
class C { int c1, c2; public: int getC1() { return c1; } int getC2() { return c2; } };
vector<A*> v; void p() { .... v[i]->getC1(); ... v[i]->getC2(); ... }
Not going to work. If C and B are so different, they have no business to
reside in the same container to begin with. The only reason for B and C
to have a base class is if they have something _in common_. If they have
_nothing_ in common, what polymorphism can we talk about here?
Of course, you could try to claim that they have the _name_ in common, but
come on, what polymorphism is there if the only thing they share is the
ability to have a name? If that's so, the only thing you can do with them
polymorphically is to learn the names of the objects.
And another question:
list<A*> l; A* p = new C(...); l.push_front(p) ; l.pop_front();
is *p destroyed?
No.
Or even more: will list<A*>'s destructor destroy all the elements of l ?
No, it will not. It has to be done manually (since it was allocated
without 'list's involvement, the list has no business trying to free
them.
V Not going to work. If C and B are so different, they have no business to reside in the same container to begin with. The only reason for B and C to have a base class is if they have something _in common_. If they have _nothing_ in common, what polymorphism can we talk about here?
Of course, you could try to claim that they have the _name_ in common, but come on, what polymorphism is there if the only thing they share is the ability to have a name? If that's so, the only thing you can do with them polymorphically is to learn the names of the objects.
That was only an example; classes A,B and C have many things in common.
Actually their only difference is what I show in that example.
Nafai wrote: Not going to work. If C and B are so different, they have no business to reside in the same container to begin with. The only reason for B and C to have a base class is if they have something _in common_. If they have _nothing_ in common, what polymorphism can we talk about here?
Of course, you could try to claim that they have the _name_ in common, but come on, what polymorphism is there if the only thing they share is the ability to have a name? If that's so, the only thing you can do with them polymorphically is to learn the names of the objects.
That was only an example; classes A,B and C have many things in common. Actually their only difference is what I show in that example.
Well, then it's not fair to talk about them out of context...
The whole idea of using containers with polymorphic types is that the
objects (through pointers) are used polymorphically . As soon as you have
to figure out the "real" types of objects via some kind of RTTI (your 'if
name is "I am B" ' _is_ RTTI, in essence), you step away from polymorphic
behaviour.
Yes, you can always do
if (v[i]->is_really_of_t ype_B()) { // whatever 'is_really_of_t ype_B' is
B* pb = dynamic_cast<B* >(v[i]);
// use pb however you want
}
else if (v[i]->is_really_of_t ype_C()) { // same here
C* pc = dynamic_cast<C* >(v[i]);
... et cetera ...
Hell, you can write
if (B* pb = dynamic_cast<B* >(v[i])) {
// use pb
}
else if (C* pc = dynamic_cast<C* >(v[i])) {
// use pc
}
and so on. But both approaches _require_ that you know what types derive
from 'A' _ahead_of_time_ , while writing that code. What if I come later
and derive another type from A and want to store it in the same container?
SOL? Or do I have to come in and edit that function and every piece of
code that does that?
While it is possible to circumvent polymorphism in C++, you should
definitely think twice before writing code like that. Write some kind of
special processing code in the base class and make every derived class
override that thus providing _polymorphic_ processing.
You either put effort initially to _keep_ polymorphism, to adhere to OOD
principles, or you don't, then somebody else or maybe you will have to
put some effort _later_ to keep the system working.
V
"Nafai" <na*******@yaho o.es> wrote in message
news:rK******** ***********@tel enews.teleline. es... Hello. I'll try to explain my problem with an example:
I have the following classes:
class A { public: string name; ... };
class B : public A { B(int x) {b=x; name="I am B"; } int b; getB() { return b }; };
class C : public A { C(int x) {c=x; name="I am C"; } int c; getC() { return c; } };
Now, I need a vector<A*> v;
An there is a function like the following:
void p() { ... if(v[i]->name=="I am B"){ v[i]->getB() ...}; ... if(v[j]->name=="I am C") { v[j]->getC() ... }; ... };
It doesn't work because v contains objects of class A, but A doesn't implement getB() nor getC(). But I need to have in the same vector objets of A, B and C. And I don't want to declare getB and getC as virtual in A, because these methods will only be defined in classes B and C respectively.
How can I do that?
You would come up with some other function name that makes sense in the general
case for all subtypes. What does it do? It just returns a value, that both B
and C seem to share. You haven't given enough information, but right off the
top if my head, I'd say take out "int c" and "int b" and put "int value" in A
instead. Then write a function "getValue" for A, and take out getB and getC.
Then you can write your code as such:
void p()
{
v[i]->getValue();
}
*That* is the point of polymorphism. No "ifs" for the type.
"Nafai" <em***@company. com> wrote in message
news:rE******** ***********@tel enews.teleline. es... Not going to work. If C and B are so different, they have no business
to reside in the same container to begin with. The only reason for B and C to have a base class is if they have something _in common_. If they
have _nothing_ in common, what polymorphism can we talk about here?
Of course, you could try to claim that they have the _name_ in common,
but come on, what polymorphism is there if the only thing they share is the ability to have a name? If that's so, the only thing you can do with them polymorphically is to learn the names of the objects.
That was only an example; classes A,B and C have many things in common. Actually their only difference is what I show in that example.
There are several ways of doing this:
This way you can sort of downcast without using dynamic_cast, and you know
which classes you allow to cast to in class A. (this is what is done in the
composite pattern)
class C;
class B;
class A {
public:
virtual C* GetC() { return 0; };
virtual B* GetB(){ return 0; };
};
class B : public A{
public:
virtual B* GetB(){ return this; };
};
class C : public A{
public:
virtual C* GetC(){ return this; };
}
or you can implement methods that do nothing on the base class, and has
functionality on some of the derived...
(this is done in state pattern)
class A {
public:
virtual void doStuffB{};
virtual void doStuffC{};
};
class B: public A {
int x_;
public:
virtual void doStuffB{ x_ = 10; };
};
class C: public A {
int y_;
public:
virtual void doStuffC{ y_ = 10;};
};
You can probably solve this in more ways, but what ever way you choose to
solve it, the cleanest one would be to keep the interface between the base
class and its derivee's 100%. You might be able to use use template method
if you want something extra to happen in a derived class.. If you have a
need to add a function, that has nothing to do with the rest of the
hierachy, then take a look at the hierachy again, you might need to refactor
it..
Nafai wrote:
[snip]
What is poliporphism? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Richard Galli |
last post by:
I want viewers to compare state laws on a single subject.
Imagine a three-column table with a drop-down box on the top. A viewer
selects a state from the list, and that state's text fills the column below.
The viewer can select states from the drop down lists above the other two
columns as well. If the viewer selects only one, only one column fills. If
the viewer selects two states, two columns fill. Etc.
I could, if appropriate, have...
|
by: FreeStyle |
last post by:
Hi everybody,
I'm using phpMyAdmin 2.2.6 with EasyPHP v.1.6.0.0
I wrote a php script which uses a username (added in the mysql base with
phpMyAdmin).
This user has no privileges.
But in the script, I have the following request for the same username :
INSERT TO table (...) VALUES (....)
And it's working !!! The user can insert new rows with the php script to
the database and
he has no privileges. How it can be possible ?
|
by: Marcus |
last post by:
I'm really confused with something I never had any problems with
before... I have a form with a textbox called password. On the second
page that $password is posted to, if I test isset($password) after a
submit, it always evaluates to true, regardless of whether or not
anything was entered into the textbox... echoing the value simply echoes
its contents, which is an empty string. If I test for simply
if($password), however, that does...
|
by: fartsniff |
last post by:
hello all,
here is a preg_match routine that i am using. basically, $image is set in
some
code above, and it can be either st-1.gif or sb-1.gif (actually it randomly
picks
them from about 100 gifs).
then it processes them based off of which image type it selected, either the
st- 's or
the sb- 's.
|
by: Fredrik Jonson |
last post by:
Hello,
I'm writing a newsletter poster for a website. I have some
html news items which I want to turn into plain text and prettify
before emailing it.
Now, i have found wordwrap and strip_tags so the only problem
remaining is the links. Below you see what I like to see, but
I haven't got a clue how to get there.
| |
by: Aldo Polli |
last post by:
Hi,
I have this error when I start apache2 with php4
Syntax error on line 233 of /mypath/apache2/conf/httpd.conf:
Cannot load /mypath/apache2/modules/libphp4.so into server: dynamic linker:
/mypath/apache2/bin/httpd: relocation error: symbol not found:
ap_pass_brigade; referenced from: /mypath/apache2/modules/libphp4.so
I compile apache 2.0.46 with
|
by: Marcus |
last post by:
I am having some problems with trying to perform calculations on time
fields. Say I have a start time and an end time, 1:00:00 and 2:30:00
(on a 24 hour scale, not 12). I want to find the difference in minutes,
divide this result by a predefined size of interval, and make a loop
that runs this many times. For example, with an interval size of 15
minutes, it will return 6 blocks... I have this all working fine, but am
getting stuck on...
|
by: phpkid |
last post by:
Howdy
I've been given conflicting answers about search engines picking up
urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3
Do search engines pick up these urls?
I've been considering converting a site of mine to PHP-Nuke, but if
the individual modules aren't picked up in search engines I'm not
going to do it.
Thanks
phpKid
|
by: Randell D. |
last post by:
Folks,
I have a string that *could* contain any character - I want it to call a
function that will allow me to pass the variable, and then return it cleaned
of anything except alphanumeric, dots, dashes and commas... How would I do
this? I have a feeling preg_replace is what I need to use but regular
expressions have always been over my head. I do know the syntax though
(taken from a previous posting made some weeks ago) that I've been...
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |