g++ -std=gnu++0x main.cpp
In file included from main.cpp:6:0:
CustArray.h: In constructor 'CustArray::CustArray()':
CustArray.h:26:32: error: 'class Info' has no member named 'someInfo'
make: *** [all] Error 1
/*
* Info.h
*
*/
#ifndef INFO_H_
#define INFO_H_
class Info
{
friend class CustArray;
};
#endif /* INFO_H_ */
/*
* SubInfo.h
*
*/
#include "Info.h"
class SubInfo : public Info
{
const int someInfo;
public:
SubInfo(const int someInfo):someInfo(someInfo){}
};
#include <vector>
#include <memory>
#include "Info.h"
#include "SubInfo.h"
template<typename T>
struct ptrModel
{
typedef std::unique_ptr<T> Type;
};
//Alias shortener.
typedef ptrModel<Info>::Type ptrType;
class CustArray
{
protected:
std::vector<ptrType> array;
public:
CustArray()
{
ptrType el_init(new SubInfo(1));
array.push_back(std::move(el_init));
int someInfo = (*(array[0])).someInfo;
}
};
/*
* main.cpp
*
*/
#include "CustArray.h"
#include <vector>
int main()
{
CustArray seq;
return 0;
}
An
std::vector< std::unique_ptr<Base> >is just that: a vector filled with pointers to bases. And you cannot access derived class’ content through base class pointers/references – even if objects of derived classes are behind those pointers/references.This is no different from this:
That doesn’t mean that behind
infothere isn’t a derived class’ object. There is. But you cannot access anything of it but what’s available through the base class interface. That’s basic OO.