C++: How to implement a pointer to another class as a member?

74 Views Asked by At

I want to implement a class "class_B" that contains a pointer to an instance of another class "class_A" so that it can also access its member function. However, I do not know how to implement this. Below you can find my minimum working example. Could you please tell me what I am doing wrong?

#include <iostream>


class Class_A
{

public:
  int number_;

  // Here we define the constructor for "Class_A".
  Class_A(int a)
  {
    number_ = a;
  }

  void printNumber()
  {
    std::cout << "The value in Class_A is " << number_ << std::endl;
  }
};


class Class_B
{
public:
    Class_A* class_A_instance;

    // Here we define the constructor for "Class_B".
    Class_B(int b)
    {
      class_A_instance = Class_A(b);
    }
};


int main()
{
  Class_B class_B_instance(3);
  class_B_instance::class_A_instance::printNumber();

  return 0;
}
2

There are 2 best solutions below

4
manuel On BEST ANSWER

I think you want to initialize your Class_A instance on the heap with new. Then call the non-static member class a instance of Class_B instance:

#include <iostream>


class Class_A
{

public:
  int number_;

  // Here we define the constructor for "Class_A".
  Class_A(int a)
  {
    number_ = a;
  }

  void printNumber()
  {
    std::cout << "The value in Class_A is " << number_ << std::endl;
  }
};


class Class_B
{
public:
    Class_A* class_A_instance;

    // Here we define the constructor for "Class_B".
    Class_B(int b)
    {
      class_A_instance = new Class_A(b);
    }
};


int main()
{
  Class_B class_B_instance(3);
  class_B_instance.class_A_instance->printNumber();

  return 0;
}
0
Remy Lebeau On

A pointer needs to point at something, but you are not assigning the pointer correctly. You are creating a temporary Class_A object and assigning it directly to the pointer, instead of assigning the address of that object instead.

Also, you are not calling the printNumber() method via the pointer correctly, either.

You would need something more like this:

...

class Class_B
{
public:
    Class_A* class_A_instance;

    Class_B(int b)
    {
      class_A_instance = new Class_A(b);
    }

    /* alternatively:
    Class_B(int b) :
      class_A_instance(new Class_A(b))
    {
    }
    */

    ~Class_B()
    {
      delete class_A_instance;
    }
};

int main()
{
  Class_B class_B_instance(3);
  class_B_instance.class_A_instance->printNumber();

  return 0;
}

However, a better solution in this particular example would be to simply not use a pointer at all, eg:

...

class Class_B
{
public:
    Class_A class_A_instance;

    Class_B(int b) : class_A_instance(b) {}
};

int main()
{
    Class_B class_B_instance(3);
    class_B_instance.class_A_instance.printNumber();

    return 0;
}