hello
hello

Reputation: 1228

How to return an object of a class whose object is parameter inside another struct

If I have a class structure such as:

class Data
{
public:
   Data(int a, int b) : mem_a(a), mem_b(b) {  };
private:
   int mem_a;
   int mem_b;
}

class UseData
{
public:
    UseData() {  };
    Data* returnDataObj(int c) { return DataObj; }
private:
   struct node
   {
      Data dat;
      node* next;
      node(const Data aData) : dat(aData), next(NULL) {  };
   }
   node** table;
}

Inside returnDataObj, I have somthing that looks like:

Data* UseData::returnDataObj(int c)
{
    node* head = table[c];
    if(head == NULL)
       return NULL; //<-- No issues here
    else
       return head;// I get an error on this line - return type does not match;
}

That was expected since head is of type node. Is there a way I can return type Data from returnDataObj ?

Upvotes: 1

Views: 57

Answers (1)

Will Custode
Will Custode

Reputation: 4594

You method should be updated to return &head->dat, which is of the same type that the method is declared to return.

Data* UseData::returnDataObj(int c)
{
    node* head = table[c];

    if(head == NULL)
       return NULL;
    else
       return &head->dat;
}

Currently you are trying to return just head which is of type node*. Clearly you can see the type mismatch.

Upvotes: 2

Related Questions