Vector casting help

OOBradm

Golden Member
May 21, 2001
1,730
1
76
#include <iostream>
#include <vector>
using namespace std;



class superClass {
public:
int superNumber;
};



class subClass: public superClass {
public:
int subNumber;
};



int main() {


////////a vector of subclasses
std::vector<subClass> subvector;



//////////make an instance of subclass and superclass
subClass subclass;
superClass superclass;



//////////add a subclass to the subclass vector
subvector.push_back( subclass );


////////// and now the part i want to know...
////////// make a vector of superclass pointer, and have it point to a
////////// vector of subclasses.... should work?????
////////// code compiles, but i can only access the first vector in the subclass
////////// vector using the superclass vector pointer.... why?
std::vector<superClass> * supervector;
supervector = (std::vector<superClass>*)&subvector;


return 1;
}
 

slugg

Diamond Member
Feb 17, 2002
4,723
80
91
its been a good while since ive touched C++ (im a java guy myself), but it seem like that cast should work. Weird. Have you tried

std::vector<superClass> * supervector = &subvector;

? My guess (and i dont have a compiler on me right now, so i cant try sorry) would be that you're already creating the superClass pointer "supervector" (which the compiler will now take as it only points to superClass objects)... so now you just give it a reference. I don't think you actually have to cast your "subvector" object since all you're doing is passing a reference (hence the &). So i dunno, try that? If not, don't know what to tell you :p
 

Neverm1nd

Member
Jul 3, 2006
42
0
0
did you mean to do
subvector.push_back( superclass );
right below
subvector.push_back( subclass ); ?

because there's only one item in the vector