简体   繁体   中英

Trying to assign derived class object address to vector of base class pointers

I have two classes set up as below

class A
{}

class B : A
{}

And was trying to have a vector that could hold any object of class A or it's derived types using pointers. I tried to do:

vector<A*> objectsvar;

B var1();

objectsvar[0] = var1;

// Also tried = *var1;

Is there any way to do this sort of thing? to have a container that can hold any of type A or it's derived classes without loosing anything?

Yes, you can do this. Unfortunately, as has already been pointed out in the comments, you made several mistakes trying to implement it:

  • B var1(); does not call the default constructor but declares a function.

  • To add an element to a vector, use push_back (or insert , emplace or emplace_back ). In your case, the subscript operater tries to access an element that is not there.

  • To get the address of a variable, use & . * does the exact opposite, it dereferences a pointer.

What you want is:

vector<A*> objectsvar;
B var1;
objectsvar.push_back(&var1);

Use the uniform initializer {} instead:

B var1{};

Saying B var1(); declares a function in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM