A pointer return method that points to an array object declared in another header,

I am a bit stuck in two confused issues.

  • First, I want to have an array of pointers to objects on the heap. (objects declared in a different header)

  • Secondly, I want the method to return a pointer to one of these objects.

My current code is the result of some grunts and will fail because I cannot use the bar as the return type without declaring it completely. But I do not see how else to solve the problem. I tried to make "getBar" a function pointer, but then I do not know how to make it available ** barArray if it is not a member method.

Any help would be greatly appreciated: D

My code is:

foo.h

#ifndef FOO_H
#define FOO_H

//forward declaration
class bar;

class foo  
{  
    public:  
        //constructor
        foo(int x);  
        //method
        bar * getBar(int y);  
    private:  
        int howManyBars;
        bar **barArray;  
};

#endif

foo.cpp

#include "foo.h"
#include "bar.h"  

//constructor
foo::foo(int x)
{
    howManyBars = x;
    barArray = new bar *[howManyBars];

    for (int i=0; i < howManyBars ; i++)
    {
        barArray[i] = NULL; //set all pointers to NULL
    }
}

//method
bar * foo::getBar(int y)
{
    y = (y - 1);
    // if the pointer is null, make an object and return that
    if (barArray[y] == NULL)
    {
        barArray[y] = new bar();
    }
    return barArray[y];
}

bar.h

#ifndef BAR_H
#define BAR_H

#include <iostream>

class bar
{
    public:
        void test(){std::cout << "I'm alive!\n";};
};
#endif
+3
1

, :

  • bar .
  • bar * foo:getBar(int y)

:

bar * foo::getBar(int y)

3.

bar[i] = NULL; //set all pointers to NULL

:

barArray[i] = NULL; //set all pointers to NULL
+1

Source: https://habr.com/ru/post/1779526/


All Articles