big boi
big boi

Reputation: 37

How do I reference another class into another class in C++?

I've been trying to reference another class inside of a class in C++ and I have no idea how. I have created a small program to demonstrate the issue

#include <iostream>
class foo{
    public:
    int variable1 = 012;
};

class bar{
    public:
    int getFooVariable(){
        return variable1; // How would I get bar to refrence foo in foobar?
    }
};

class foobar{
    public:
    bar p1;
    foo p2;
};

int main(){
    foobar fb;
    std::cout << fb.p1.getFooVariable(); << std::endl;
    return 0;
}

How would I solve this problem?

Upvotes: -1

Views: 1433

Answers (2)

Soleil
Soleil

Reputation: 7287

You're looking for dependency injection:

class foo
{
public:
    int variable1 = 012;
};

class bar
{
    foo _foo;
public:
    bar(foo& fooInjected) :
        _foo(fooInjected)
    {}
    int getFooVariable() { return _foo.variable1; }
};

There is an idea of inversion of control: bar has no control over the creation of foo instance, which is created outside. It's a common way to inject for instance a service. It's also a very important way to loosely couple classes working together and to mock and to test them. But here foo is a concrete class, instead and ideally you're refering only an interface (c#) or an abstract class (c++) in bar. Which concrete class is behind is out of control of bar. I recommend M. Seeman's book Dependency Injection in .NET to understand this completely.

or inheritance:

class foo
{
public:
    int variable1 = 012;
};

class bar: public foo
{
public:
    int getFooVariable() { return variable1; }
};

Here, bar builds up heavily on foo. bar is a "richer version" of foo if this makes sense. This is what to choose if there is a high cohesion inside bar.

Invoking a variable through another's instance function is a most horrid idea, that goes against class cohesion:

int getFooVariable(foo* foo) { return foo->variable1; }

Upvotes: 2

user1322654
user1322654

Reputation:

Sorry to change the formatting, here's a solution:

#include iostream
class foo
{
public:
    int variable1 = 012;
};

class bar
{
public:
    int getFooVariable(foo* foo)
    {
        return foo->variable1; // How would I get bar to refrence foo in foobar?
    }
};

class foobar
{
public:
    bar p1;
    foo p2;
};

int main()
{
    foobar fb;
    std::cout << fb.p1.getFooVariable(&(fb.p2));
    << std::endl;
    return 0;
}

You can add a parameter to the getFooVariable() function to take a foo* reference. The reference can be found when you call the function.

Upvotes: 0

Related Questions