views:

52

answers:

3
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;
}
+4  A: 

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:

SubInfo si(1); 
Info& info = si;
info.someInfo; // won't compile

That doesn't mean that behind info there 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.

sbi
+1  A: 

No, you have a pointer to the base class Info, which as the compiler says, doesn't have a member named someInfo. That pointer still points to a SubInfo, but you can't access derived class members through a base class pointer.

If you really need access to the field, you would need to use dynamic_cast to downcast. Be sure to check the result to ensure the cast is valid.

Nick Meyer
+1  A: 

What it's saying is true

error: 'class Info' has no member named 'someInfo'

It doesn't. You can not access child members in a polymorphic way like you are attempting.

You will need a virtual member function in the class Info such as GetSomeInfo() which can either be pure virtual or return something interesting in the base class. Then in the child class it can return someInfo

Salgar