www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/03/03/10:21:35

From: mksmith AT idirect DOT com (Martin Smith)
Newsgroups: comp.os.msdos.djgpp
Subject: vectors of derived objects
Message-ID: <3aa1079f.55821769@news1.on.sympatico.ca>
X-Newsreader: Forte Free Agent 1.21/32.243
Lines: 36
Date: Sat, 03 Mar 2001 15:11:39 GMT
NNTP-Posting-Host: 64.231.2.107
X-Trace: news20.bellglobal.com 983632299 64.231.2.107 (Sat, 03 Mar 2001 10:11:39 EST)
NNTP-Posting-Date: Sat, 03 Mar 2001 10:11:39 EST
Organization: Sympatico
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

The vector<class T> template apparently casts all elements in the
vector as base objects in the situation where class T has classes
derived from it.  

I would like to ba able to have the vector elements be able to use
virtual function calls, so I guess the question is whether there is
another template other than vector that I don't know about.

In the example follows, I want the derived list member to output
"DERIVED" 

#include <iostream>
#include <vector>

class base {
public:
  virtual void show() { cout << "BASE" << endl; }
};

class derived : public base {
public:
  void show() { cout << "DERIVED" << endl; }
};

main() {

  vector<base> list;

  base b;  list.push_back(b);

  derived a;  list.push_back(a);

  list[0].show();    // output is "BASE"
  list[1].show();    // output is "BASE"

}

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019