• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Vector casting help

OOBradm

Golden Member
#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;
}
 
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 😛
 
did you mean to do
subvector.push_back( superclass );
right below
subvector.push_back( subclass ); ?

because there's only one item in the vector
 
Back
Top