473,320 Members | 2,027 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

std::vector of references to derived class objects

14
Hi All,
Here is the basic example of the using polymorphism. And then my question is below.
Expand|Select|Wrap|Line Numbers
  1.  typedef std::vector<Vehicle*>  VehicleList;
  2.  
  3.  void myCode(VehicleList& v)
  4.  {
  5.    for (VehicleList::iterator p = v.begin(); p != v.end(); ++p) {
  6.      Vehicle& v = **p;  // just for shorthand
  7.  
  8.      // generic code that works for any vehicle...
  9.      ...
  10.  
  11.      // perform the "foo-bar" operation.
  12.      v.fooBar();
  13.  
  14.      // generic code that works for any vehicle...
  15.      ...
  16.    }
  17.  }
  18. ===================
  19.  class Car : public Vehicle {
  20.  public:
  21.    virtual void fooBar();
  22.  };
  23.  
  24.  void Car::fooBar()
  25.  {
  26.    // car-specific code that does "foo-bar" on 'this'
  27.    ...  ← this is the code that was in {...} of if (v is a Car)
  28.  }
  29.  
  30.  class Truck : public Vehicle {
  31.  public:
  32.    virtual void fooBar();
  33.  };
  34.  
  35.  void Truck::fooBar()
  36.  {
  37.    // truck-specific code that does "foo-bar" on 'this'
  38.    ...  ← this is the code that was in {...} of if (v is a Truck)
  39.  } 
So, in this example, instead of std::vector<Vehicle*>, can I use std::vector<Vehicle> and still achieve the polymorphism, like calling the function of the derived class object reference it contains??

Can you give an example of the same.

Thanks
rsennat
Aug 13 '08 #1
5 2572
arnaudk
424 256MB
C++ does not fully support the Liskov substitution principle; you can substitute the address of objects of derived classes in place of the base class pointer, but not derived objects themselves in place of a base class, so the answer to your question is: No.

Some minor comments:
line 6: Why not use a different local variable name to avoid confusion with the outer variable v?
line 12: I would avoid the shorthand altogether and just use (*p)->fooBar();
Aug 13 '08 #2
weaknessforcats
9,208 Expert Mod 8TB
You will not be able to use anyt Truck methods if you have a vector<Vehicle>.

That's becuse the Truck-part of the object was sliced off when the the object was put in the vector.

Polymorphism in C++ only works if you have a pointer or reference to the object.

You should have a vector<Vehicle*>, or better, a vector of handles to Vehicle.

Read this: http://bytes.com/forum/thread651599.html.
Aug 13 '08 #3
rsennat
14
You will not be able to use anyt Truck methods if you have a vector<Vehicle>.

That's becuse the Truck-part of the object was sliced off when the the object was put in the vector.

Polymorphism in C++ only works if you have a pointer or reference to the object.

You should have a vector<Vehicle*>, or better, a vector of handles to Vehicle.

Read this: http://bytes.com/forum/thread651599.html.
Thanks for the information.
And I have one more related query, if polymorphism works with reference to an object, then can we use like this, vector<Vehicle&>?
Aug 13 '08 #4
weaknessforcats
9,208 Expert Mod 8TB
Yes, you can.

The essential thing here is that a Vehicle* or a Vehicle& do not require a copy of the object. Once that Truck is copied as a Vehicle, the Truck portion is sawed off. Technically, this is called slicing and it's usually a bad sign.

Once you start using Vehicle* or Vehicle& in your vector, be sure those objects are always on the heap. That way you have control over deletion and not the compiler.

It won;t be long after this that you will start using Handles to a Vehicle.

And shortly after that, you will add a method to a Truck and you can't call it using a Vehicle* or Vehicle&. Therefore, you should design for a Visitor right up front. Read this: http://bytes.com/forum/thread674645.html.
Aug 13 '08 #5
rsennat
14
Yes, you can.

The essential thing here is that a Vehicle* or a Vehicle& do not require a copy of the object. Once that Truck is copied as a Vehicle, the Truck portion is sawed off. Technically, this is called slicing and it's usually a bad sign.

Once you start using Vehicle* or Vehicle& in your vector, be sure those objects are always on the heap. That way you have control over deletion and not the compiler.

It won;t be long after this that you will start using Handles to a Vehicle.

And shortly after that, you will add a method to a Truck and you can't call it using a Vehicle* or Vehicle&. Therefore, you should design for a Visitor right up front. Read this: http://bytes.com/forum/thread674645.html.
Oh ok. Thanks a lot for all the information.
Aug 13 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Jason Heyes | last post by:
I wrote a previous post that asked whether there was a reference-counted implementation of std::vector. Apparantly there wasn't. So my next question is, is it possible to write your own shared...
3
by: Chris | last post by:
Hi, I'm playing/developing a simple p2p file sharing client for an existing protocol. A 2 second description of the protocol is Message Length = int, 4 bytes Message Code = int, 4 bytes...
5
by: Ernst Murnleitner | last post by:
Hello, is it possible to derive from std::vector and derive also its iterator? If I do it like in the example below, I get a problem when I need the begin of the vector: begin() returns the...
5
by: canned.net | last post by:
I have a class Scene that has several subclasses: World, Vault, etc. I fill a vector with these classes and then cannot go through and delete them. What's the trick to deleting pointers from a...
17
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling...
3
by: Pelle Beckman | last post by:
Hi all, I have a few - beginners - questions: * Why can't I put object references in a std::vector, i.e std::vector<MyClass&> ? At least in doesnt work in gcc (mingw, win32) * What's the...
9
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...
6
by: lokchan | last post by:
i want to create a vector of pointer s.t. it can handle new and delete but also have std::vector interface can i implement by partial specialization and inherence like follow ? #include...
7
by: Thomas | last post by:
I am compiling with g++ the fol. class: template<typename E> class C_vector_ : public std::vector<E> { private:
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.