Chris Jones
Chris Jones

Reputation: 57

C++ pass by reference - can this be done?

I have several files which is causing a compile error, can the following be done?

header1.h

class Class1{
public:
void function1(Class1 &);
};

header2.h

class Class2{
public:
void function2(Class2 &, Class1 &);
};

cpp2.cpp

#include "header2.h"
void Class2::function2(Class2 & my2Class, Class1 & my1Class){};

main.cpp

#include "header1.h"
#include "header2.h"

// functions

The error is stating that header2.h knows nothing of Class1 as a type. How can I declare an object of type Class1 in this header file, without using an include or without putting both classes in the same file (they are entirely separate and should only meet inside functions called within main)?

Thanks!

Upvotes: 1

Views: 2738

Answers (2)

Oofpez
Oofpez

Reputation: 514

let every header include each other header that it requires information about, but with a preprocessing definition to avoid circular references or repeated declarations. e.g. header2 should be

#ifndef FUNCS_H

#define FUNCS_H

#include "header1.h"

    class Class2{
    public:
    void function2(Class2 &, Class1 &);
    };
#endif

This is how I do all my headers in C++

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258648

You can use forward declarations:

class Class1; //forward declare Class1
class Class2{
public:
void function2(Class2 &, Class1 &);
};

Passing a parameter of a type to a function doesn't require the type to be fully defined.

Upvotes: 7

Related Questions