Search code examples
c++classvariablesvectornested

How to extract data from an inherited class template in C++


I'm writing a vector of class objects that each holds a Template variable in C++ so that it allows me to process different types of data.

I'm using the following code:

#include <iostream>
#include <memory>
//Declare Vector library to work with vector objects.
#include <vector>
#include <string>
    
using namespace std;

class AItem{
};
    
template <class OBJ>
    
//Object that will hold template data.
class Item : public AItem {
    public:
        //Variable to store the values. TODO: Verify if this can be made into a TEMPLATE to accept any value.
        OBJ value;
    
        //Constructor to store values.
        Item(OBJ _value): value(_value){}

        ~Item(){ 
            cout << "Deleting " << value << "\n";
        }
};

//Main Thread.
int main(){
    //##################################################
    //##################################################
    //                TEST SECTION

    //Create new Items.
    Item<string> *itObj = new Item<string>("TEST");
   //Create a Vector that stores objects.
    vector <shared_ptr<AItem>> v1;

    //Store each item in the Array.
    v1.push_back(shared_ptr<AItem>(itObj));

    //cout<<&v1.getValue()<<"\n";

    //Iterate through each one and retrieve the value to be printed.
    //TODO: FIX THIS
    for(auto & item: v1){
        cout<<item<<'\n';
    }
    //##################################################
    //##################################################
    cout<<"Cpp Self Organizing Search Algorithm complete.\n";
    return 0;
}

and I want to retrieve the inserted value, but whenever I iterate whether I use pointer or access the data, I only get a memory address or I'm told that class AItem has no property value. What is the proper way to access variables in nested classes in C++?


Solution

  • Maybe it's because you didn't define some virtual function in the parent class, like this?

    struct AItem {
      virtual void a() { printf("AItem::a()\n"); }
      virtual void b() { printf("AItem::b()\n"); }
    };
    template <class OBJ> struct Item : public AItem {
    public:
      OBJ value;
      Item(OBJ _value) : value(_value) {}
      void a() override { printf("Item::a()\n"); }
      void b() override { printf("Item::b()\n"); }
      ~Item() { std::cout << "Deleting " << value << "\n"; }
    };
    /* Use it like below
    for (auto &item : v1) {
      item->a();
      item->b();
    }
    */