windy401
windy401

Reputation: 197

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?

Upvotes: 0

Views: 35

Answers (2)

Knoep
Knoep

Reputation: 890

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 (orinsert, 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);

Upvotes: 1

user8782808
user8782808

Reputation:

Use the uniform initializer {} instead:

B var1{};

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

Upvotes: 0

Related Questions