user2924459
user2924459

Reputation: 23

C++ Instantiating a different class from a function in a class

I have a "Foo.cpp" class and a "Bar.cpp" class. I want to overload the + operator on two arguments of Foo so that adding two Foos returns a Bar with a value that's the product of their values. The code looks like

//Foo.h
class Foo
{
public:
    double foo_val;
    Foo();
    Foo(double);
};

Bar* operator+ (Foo&, Foo&)

.

//Foo.cpp
#include "Foo.h"

Foo::Foo(){foo_val = 0;}
Foo::Foo(double d){foo_val = d;}

Bar* operator+ (Foo& f1, Foo& f2){
    return new Bar(f1.foo_val*f2.foo_val);
}

.

#include "Foo.h"
#include "Bar.h"
int main(){
    Foo f1 = new Foo(4, 5);
    Foo f2 = new Foo(1, 2);
    Bar = f1+f2;
}

Bar is basically identical to Foo at the moment, and it has a constructor "Bar(double);"

It doesn't work at the moment, I think because Bar hasn't been defined before I try to make a new one. (The compiler error is "'Bar' does not name a type") However, I know I can't forward declare Bar at the top because that only works for pointers, whereas I'm trying to construct a new one. Is there some way to get this type of thing to work, or am I going about this totally wrong?

Thanks!

Upvotes: 2

Views: 70

Answers (2)

Paul Draper
Paul Draper

Reputation: 83205

There are two options.

(1) Put

#include "Bar.h"

at the beginning of Foo.h. But if Bar.h already has #include "Foo.h", this will cause a circular dependency, so this is not a viable option.

(2) Put

class Bar;

in Foo.h, before the class definition of Foo.

Upvotes: 0

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67137

It's actually very simple. In Foo.h, you need to forward declare class Bar, so that the declaration of operator+ is valid:

class Bar;

class Foo
{
    // ...
};

Bar* operator+ (Foo& f1, Foo& f2);

Then, in Foo.cpp, you need to include Bar.h since here you really need to know how Bar is declared:

#include "Foo.h"
#include "Bar.h"

// ...

Bar* operator+ (Foo& f1, Foo& f2)
{
    // Now you can use Bar's constructor
    return new Bar(...);
}

Upvotes: 2

Related Questions