473,698 Members | 2,491 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HELP: vector & polymorphism

I can't understand why in this folling example the message
"Base.Draw( )" is printed. Shouldn't "Derive.Dra w" be printed because
of polymorphism? How can I rewrite this example using a vector to
achieve polymorphism. Help!!! I'm very confused.

//Base class.
class Base
{
public:
Base()
{}

virtual void Draw()
{
cout << "Base.Draw()\n" ;
}
};

//Derive class.
class Derive: public Base
{
public:
Derive()
{
}

void Draw()
{
cout << "Derive.Draw()\ n";
}
};

//Define the name space to use.
using namespace std;
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp;
//Add derive object.
Derive d1;
temp.push_back( d1 );

//Add another derive object.
Derive d2;
temp.push_back( d2 );

//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x].Draw();
}

//Pause the DOS command window.
system("PAUSE") ;

//Return system status.
return 0;
}
Jul 22 '05 #1
4 2577
"The Directive" <th***********@ hotmail.com> wrote in message
news:84******** *************** ***@posting.goo gle.com
I can't understand why in this folling example the message
"Base.Draw( )" is printed. Shouldn't "Derive.Dra w" be printed because
of polymorphism? How can I rewrite this example using a vector to
achieve polymorphism. Help!!! I'm very confused.

//Base class.
class Base
{
public:
Base()
{}

virtual void Draw()
{
cout << "Base.Draw()\n" ;
}
};

//Derive class.
class Derive: public Base
{
public:
Derive()
{
}

void Draw()
{
cout << "Derive.Draw()\ n";
}
};

//Define the name space to use.
using namespace std;
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp;
//Add derive object.
Derive d1;
temp.push_back( d1 );

//Add another derive object.
Derive d2;
temp.push_back( d2 );

//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x].Draw();
}

//Pause the DOS command window.
system("PAUSE") ;

//Return system status.
return 0;
}


Polymorphism only works through pointers or references. It doesn't work
through objects. Change your code to:

int main(int argc, char *argv[])
{
vector<Base*> temp;

//Add derive object pointer.
Derive d1;
temp.push_back( &d1);
//Add another derive object pointer.
Derive d2;
temp.push_back( &d2);

//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x]->Draw();
}
//Pause the DOS command window.
system("PAUSE") ;

//Return system status.
return 0;
}
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #2
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp; temp will hold Base objects only!!!!!


//Add derive object.
Derive d1;
temp.push_back( d1 ); d1 is copied to a Base object

//Add another derive object.
Derive d2;
temp.push_back( d2 ); Same thing here

//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x].Draw();

Base::Draw is called sinze temp[x] is a Base object
Suggested solution:

int main()
{
vector<Base*> temp;

// Dynamically create a Derive instance and add it to the vector
temp.push_back( new Derive);

//... add other Derive instances to vector as needed

for (size_t x=0; x < temp.size(); x++)
{
// Here, Derive::Draw is called because temp[x] is actually a pointer to
a Derive object and Base::Draw is virtual
temp[x]->Draw();
}

// Don't forget to delete dynamically created objects
for ( x=0; x < temp.size(); x++)
{
delete temp[x];
}

return 0;
}
Thierry
Jul 22 '05 #3
"The Directive" <th***********@ hotmail.com> wrote in message
news:84******** *************** ***@posting.goo gle.com...
I can't understand why in this folling example the message
"Base.Draw( )" is printed. Shouldn't "Derive.Dra w" be printed because
of polymorphism? How can I rewrite this example using a vector to
achieve polymorphism. Help!!! I'm very confused.

//Base class.
class Base
{
public:
Base()
{}

virtual void Draw()
{
cout << "Base.Draw()\n" ;
}
};

//Derive class.
class Derive: public Base
{
public:
Derive()
{
}

void Draw()
{
cout << "Derive.Draw()\ n";
}
};

//Define the name space to use.
using namespace std;
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp;
//Add derive object.
Derive d1;
temp.push_back( d1 );


At this point something rather nasty called "bit slicing" occurs. A Base
object is initialized with a Derive object. This is legal because a Derive
is a Base. However, any extra data contained in d1 is sliced off. This must
happen because temp can only hold Base objects. Thus the object which is
actually stored is a Base object, and any virtual functions will refer to
their Base incarnations.

One solution already mentioned by Thieri Miceli is to store Base pointers
rather than Base objects in the vector. This avoids bit slicing because a
Derive pointer is a Base pointer and, of course, both pointers are the same
size.

However, it does give you another problem -- where to come up with the
pointer. You can use the & operator but then you must have a place to store
the object whose address you are taking, and you must also make sure its
lifetime is at least as long as the pointer's. You can use the new()
operator but then you must take care to avoid memory leaks -- the vector
will not manage this memory for you.

A better alternative is to use a reference counted smart pointer. It looks
like this:

typedef boost::shared_p tr<Base> BasePtr;
std::vector<Bas ePtr> temp;
temp.push_back( BasePtr(new Derive));

The advantage of this arrangement is that the smart pointer will manage the
memory for you. Get boost::shared_p tr at

www.boost.org

Aside to newsgroup: What has to be done to get this into the FAQ? It
certainly is asked frequently.

[snip]

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #4
[snip]

Thanks to all. Cy, your explanation was very helpful.
At this point something rather nasty called "bit slicing" occurs. A Base
object is initialized with a Derive object. This is legal because a Derive
is a Base. However, any extra data contained in d1 is sliced off. This must
happen because temp can only hold Base objects. Thus the object which is
actually stored is a Base object, and any virtual functions will refer to
their Base incarnations.

One solution already mentioned by Thieri Miceli is to store Base pointers
rather than Base objects in the vector. This avoids bit slicing because a
Derive pointer is a Base pointer and, of course, both pointers are the same
size.

However, it does give you another problem -- where to come up with the
pointer. You can use the & operator but then you must have a place to store
the object whose address you are taking, and you must also make sure its
lifetime is at least as long as the pointer's. You can use the new()
operator but then you must take care to avoid memory leaks -- the vector
will not manage this memory for you.

A better alternative is to use a reference counted smart pointer. It looks
like this:

typedef boost::shared_p tr<Base> BasePtr;
std::vector<Bas ePtr> temp;
temp.push_back( BasePtr(new Derive));

The advantage of this arrangement is that the smart pointer will manage the
memory for you. Get boost::shared_p tr at

www.boost.org

Aside to newsgroup: What has to be done to get this into the FAQ? It
certainly is asked frequently.
It should definetely be in the FAQ.
[snip]


--The Directive
Jul 22 '05 #5

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

Similar topics

13
4617
by: Ben | last post by:
I have a program which is using a lot of memory. At the moment I store a lot of pointers to objects in std::vector. (millions of them) I have three questions: 1) Lets say the average Vector is of size 2. How much memory can I save by storing my pointers in c++ arrays, rather than vectors.
175
8805
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be changed". This is very much against my instincts. Can anyone offer some solid design guidelines for me? Thanks in advance....
15
3039
by: rwf_20 | last post by:
I just wanted to throw this up here in case anyone smarter than me has a suggestion/workaround: Problem: I have a classic producer/consumer system which accepts 'commands' from a socket and 'executes' them. Obviously, each different command (there are ~20 currently) has its own needed functionality. The dream goal here would be to remove all knowledge of the nature of the command at runtime. That is, I don't want ANY switch/cases...
9
2306
by: kathy | last post by:
I am using std::vector in my program: func() { std::vector <CMyClass *> vpMyClass; vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); //???? Required ??????????????//
13
3253
by: Fao | last post by:
Hello, I am having some problems with inheritance. The compiler does not not return any error messages, but when I execute the program, it only allows me to enter the number, but nothing else happend. I think the problem may be in my input function or in the main function. If anyone out there can help me it woul be greatly appreciated. Here is the code: #include <iostream>
14
3642
by: markww | last post by:
Hi, I want to use the vector container class to store pixel data. Currently I have some memory allocated using c++'s new operator. I allocate the memory differently based on if the pixel type is unsigned char or unsigned short like this: int nPixelType = ?; // unsigned short, or unsigned char? BYTE *pByte = NULL; switch (nPixelType) {
24
2948
by: toton | last post by:
Hi, I want to have a vector like class with some additional functionality (cosmetic one). So can I inherit a vector class to add the addition function like, CorresVector : public vector<Corres>{ public: void addCorres(Corres& c); //it do little more than push_back function. }
4
3033
by: helge | last post by:
What is the best way to implement a vector in space R3, i.e a vector holding three floats, supporting arithmetic operations, dot and cross product etc in c++? is there a standard library class for this?
5
2596
by: rsennat | last post by:
Hi All, Here is the basic example of the using polymorphism. And then my question is below. typedef std::vector<Vehicle*> VehicleList; void myCode(VehicleList& v) { for (VehicleList::iterator p = v.begin(); p != v.end(); ++p) { Vehicle& v = **p; // just for shorthand
0
8676
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
9029
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
8897
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
8867
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
7732
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
6522
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...
1
3050
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
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
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.