Question

I have an abstract class (pure virtual class/interface) that we will name A.

I have a class B that derives from A and implements the pure virtual methods of A.

I have a class C with a member that is a vector of pointers to A:

std::vector<A*> myVector

and a method:

add(A* item).

In a class D that derives from C I want to add instances/objects of class B using the add method derived from class C.

I try to write it as:

for(int i = 0; i < 10; i++)
{
    C::add( (A*) new B());
}

I am not sure if this does what I want? If I omit the (A*) I get the error:

Conversion to inaccessible base class "A" is not allowed

Did I successfully add B class object pointers to the vector?

Was it helpful?

Solution

The error

Conversion to inaccessible base class "A" is not allowed

means you're not using public inheritance when B derives from A. If you omit the public keyword when specifying class inheritance, the default inheritance is private (note that for a struct the default is public inheritance).

class B : /* private */ A

should be

class B : public A

To answer your last question:

Did I successfully add B class object pointers to the vector?

Yes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top