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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class A
{ };
class B : A
{
// memb variables and constructors
};
class C : B
{
// memb variables and constructors
};
// In main function:
vector<A*> items[50];
C* x1 = new C(1, 2);
items.push_back(&x1);
But that gives and error. Is there any way to do this sort of thing?
I also tried using random_shuffle on my A* vector and that gave an error as well, is there some problem using it with vectors of pointers?
#include <vector>
#include <memory>
#include <functional>
struct A { virtual ~A() = default ; };
struct B : A {};
struct C : A {};
struct D : C {};
int main()
{
A a ; B b ; C c ; D d ;
// fine: vector of non-owning raw pointers
std::vector<A*> items { std::addressof(a), std::addressof(b),
std::addressof(c), std::addressof(d) } ;
// fine: vector of wrapped references
std::vector< std::reference_wrapper<A> > same_items { a, b, c, d } ;
// fine: vector of owning smart pointers
std::vector< std::unique_ptr<A> > more_items ;
more_items.push_back( std::make_unique<A>() ) ;
more_items.push_back( std::make_unique<B>() ) ;
more_items.push_back( std::make_unique<C>() ) ;
more_items.push_back( std::make_unique<D>() ) ;
// **** bad ****: vector of raw owning pointers (avoid, would not pass a code review)
std::vector<A*> even_more_items { new A, new B, new C, new D } ; // not exception safe
for( auto ptr : even_more_items ) delete ptr ;
}
A is a private base class of C. What you wanted is something like this:
1 2 3 4 5 6 7 8 9 10 11 12
class A
{ virtual ~A() = default ; }; // good idea to declare a virtual destructor
class B : public A
{
// memb variables and constructors
}
class C : public B
{
// memb variables and constructors
}
#include <iostream>
#include <vector>
#include <functional> // ****class A { /* ... */ };
class B : public A { /* ... */ };
class C : public B
{
public: C( int, int ) { /* ... */ }
// ...
};
class bag
{
public:
// vector<std::reference_wrapper<A>> items[50];
std::vector< std::reference_wrapper<A> > items ; // ****
};
int main()
{
bag b ;
C c1( 1, 2 ) ;
b.items.push_back(c1);
}
If the base class A is a polymorphic type, we can invoke virtual functions on the objects and they would be dispatched at run time to the appropriate implementations.