Home > Software engineering >  Problem with copying a vector of pointers of inherited classes
Problem with copying a vector of pointers of inherited classes

Time:12-31

I have two classes, one inherits the other:

#include <iostream>
#include <vector>

class A
{
public:
    int a;
};

class B : public A
{
    void print()
    {
        std::cout << a;
    }
};

int main()
{
    A* first;
    first->a = 5;
    std::vector<B*> second;
    second.push_back( first ); // the error appears at this line
}

When I try to push_back() an element of type A* to the array of elements of type B*, the following error appears:

 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=B *, _Alloc=std::allocator<B *>]" matches the argument list
  argument types are: (A *)
  object type is: std::vector<B *, std::allocator<B *>>

Do you have any idea why this is happening?

CodePudding user response:

You can't do this.

B is an A but not the reverse.

So it would have worked only if A inherited from B.

CodePudding user response:

child class can be interpret as father class's pointer, reverse not work.

corret one may be:

#include <iostream>
#include <vector>

class A
{
public:
    int a;
};

class B : public A
{
    void print()
    {
        std::cout << a;
    }
};

int main()
{
    B* first;
    first->a = 5;
    std::vector<A*> second;
    second.push_back( first ); 
}
  • Related