Search code examples
c++pointersdeclarationdefinitions

Problems with dereferencing a class member pointer that points to another class


I have defined two simple classes. The first class (A) contains a pointer (b_ptr) to an object of the second class (B), which contains an int member (i). I created an object of the first class, and am just trying to return the int contained within the object of the pointer.

At first I could not even compile the code, but then I moved the int A::returnInt() definition so that it is after the class B definition. I am now able to compile, but I get a huge number (which changes each time I run) when I print the call to returnInt().

Any help is greatly appreciated!

// HelloWorld.cpp : main project file.
#include "stdafx.h";

using namespace System;

#include <iostream>
#include <string>
#include <vector>

using namespace std;
using std::vector;
using std::cout;
using std::endl;
using std::string;

class B;

class A {

public:
    A() = default;
    B* b_ptr;

    int returnInt();

};

class B {

public:
    B() : i(1){};
    A a;

    int i;
};

int A::returnInt() { return (b_ptr->i); };

int main()
{
    A myClass;

    cout << myClass.returnInt() << endl;

}

Solution

  • You can solve it with the following:

    #include <iostream>
    using namespace std;
    
    struct B
    {
    
        B() : i(1){}
        int i;
    };
    
    struct A
    {
      A(B& b) : b_ptr(&b) {}
    
      int returnInt() { return b_ptr->i; }
    
    private:
    
      A() = delete;
    
      B* b_ptr;
    };
    
    int main()
    {
      B b;
      A myClass(b);
    
      cout << myClass.returnInt() << endl;
    
      return 0;
    }