0

I need to build a set of classes that are dependent on each other. I am having trouble when I pass a pointer to one class to another class that is instantiated inside it.

Here an example to illustrate my problem.

#include<iostream>
#include<vector>

using namespace std;

class base;

//

 child class
    class child
    {
    public:
    child(){};
    void setPointer (base* ptr){pointer = ptr; }
    void printing(){(*pointer).print();} // error C2027: use of undefubed type base
                                        // error C2227: '.print' must have class/struct/union
private:
    base* pointer;
};

// base class
class base
{
public:
    base()
    {
        initial_vec();
        VEC[0].setPointer(this);
        VEC[0].printing();
    }

    void print() { cout <<"printing from BASE"<< endl;}

    void initial_vec ()
    {
        child child1;
        VEC.push_back(child1);
    }

private:
    vector<child> VEC;
};

int main()
{
    base b1;

    system("pause");
    return 1;
}

Do you have any idea how I achieve that without getting those errors ?

Thank you in advance

Chouaib
  • 11
  • 2

2 Answers2

0

It looks like the error you are getting it because you are trying to call printing() from your base class with only a forward declaration. To fix your problem, define the body of the function printing() after your base class has been fully defined.

Here is more details on forward declaration.

Community
  • 1
  • 1
dwcanillas
  • 3,562
  • 2
  • 24
  • 33
0

"Do you have any idea how I achieve that without getting those errors ?"

It's fairly simple. You omit the inlined codeparts that reference base, and move tem after the full declaration of the class:

#include<iostream>
#include<vector>

using namespace std;

class base;

 child class {
    public:
    child(){};
    void setPointer (base* ptr); // <<< Only declare the functions here
    void printing();

private:
    base* pointer;
};

// base class
class base {
public:
    base()
    {
        initial_vec();
        VEC[0].setPointer(this);
        VEC[0].printing();
    }

    void print() { cout <<"printing from BASE"<< endl;}

    void initial_vec ()
    {
        child child1;
        VEC.push_back(child1);
    }

private:
    vector<child> VEC;
};

Define the functions after base was fully declared:

void child::setPointer (base* ptr){pointer = ptr; }
void child::printing(){(*pointer).print();}

int main() {
    base b1;

    system("pause");
    return 1;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190