samedi 24 décembre 2022

How do I make Class A a member of Class B without inheriting it?

I have two classes (actually four, but they're not required for this). Let's call them A, and B. I am trying to declare class B as a member in class A. My problem is, I need access to a member function inside of class A from class B, but it doesn't make sense for these two classes to be inherited from each other.

Here are the two classes:

Class A:

#include "B.h"

class A {
    B test;
public:
    A() : test {this} {}

};

Class B:

#include "A.h"


class B: public Alert {
    A* test;
public:
    B() = default;
    B(A* testIn) : test{ testIn } {}

        // member functions
};

I am using Visual Studio Community Edition 2022 (64-Bit). My C++ version is C++11.

The compiler error I keep getting is "testIn undeclared identifier." This makes no sense to me, as I feel I have declared it.

I understand that making one of the classes a child of the other would allow the child class to access the public and protected members of the parent class.

The thing is, in this instance, it makes no sense for them to inherit from each other. I only need access to a function inside of class A from class B, as class A inherits from another class. I am trying to write a library, and want class A to be the class that would be used by other people. It wouldn't make any sense having class B be the class to be used in the final program. Which is why I didn't want to inherit the one from the other.

I appreciate your time for looking at my question.


Update: John's solution posted below in his own submission is correct for my original question. I am just an idiot and forgot to include that Class A also inherits from another class.

Class A would look like the following:

#include "AnotherClass.h"
#include "B.h"

class A: AnotherClass {
    B test;
public:
    A() : test {this} {}

};

Terribly sorry about my confusion. I definitely messed up.

Aucun commentaire:

Enregistrer un commentaire