1

I am very new to pointers, so I have no idea what is going on with them.

I am trying to get a master class pass a pointer of itself to its worker/s, and I have no idea why it doesn't work.

#include <iostream>
#include <Windows.h>

using namespace std;

class BigOne {
public:
    LittleOne workers[1] = {LittleOne(this)};
    int increase = 0;
};

class LittleOne {
    BigOne* master;
public:
    LittleOne(BigOne*);
    void Increment();
};

LittleOne::LittleOne(BigOne* upOne) {
    master = upOne;
}

void LittleOne::Increment() {
    master->increase++;
}

BigOne Outer;

    int main() {
    cout << Outer.increase << endl;
    Outer.worker.Increment();
    cout << Outer.increase << endl;
    system("PAUSE");
}

This is my problem boiled down to its core components.

Damon Jenkins
  • 352
  • 1
  • 3
  • 12
  • Does it give an error message? – Galik Jun 14 '18 at 05:45
  • Three things you should do with pointers: 1) forget about pointers. 2) Learn about references. 3) Learn about std::uniq_ptr and std::shared_ptr. Because you can't always forget about pointers. – Goswin von Brederlow Jun 14 '18 at 07:53
  • @GoswinvonBrederlow I didn't pay as much mind to this comment as I should have. What's wrong with vanilla pointers? – Damon Jenkins Jun 17 '18 at 00:26
  • In most cases a reference does what you want and is easier to use. For the rest managing pointers, or rather the thing they point to, is hard. If the point to static memory then they must not be freed. If they point to dynamic memory they must be freed at some point. When you pass a pointer to a function will it free it? Or will it record it somewhere for later use and freeing it will create a dangling pointer? If a function returns a pointer should you free it after use? The `std::uniq_ptr` and `std::shared_ptr` help convey who owns the pointer or outright manage the resource for you. – Goswin von Brederlow Jun 18 '18 at 08:44

2 Answers2

4

The problem isn't with pointers. It's mostly here:

class BigOne {
public:
    LittleOne workers[1] = {LittleOne(this)};
    int increase = 0;
};

When you define workers, what is LittleOne? How is it laid out in memory? How is it initialized? The compiler can't know, it hasn't seen the class definition yet. So you must flip the definitions around:

class BigOne;

class LittleOne {
    BigOne* master;
public:
    LittleOne(BigOne*);
    void Increment();
};

class BigOne {
public:
    LittleOne workers[1] = {LittleOne(this)};
    int increase = 0;
};

The forward declaration allows us to define members that accept and return pointers. So the class LittleOne can have its definition written before BigOne. And now BigOne can define members of type LittleOne by value.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

The issue is with forward declaration. You can refer the following link for more details and explanation.

What are forward declarations in C++?