Define the function outside of either class in a C++ source file, not in the header:
void OtherClass :: Othermethod() {
// call whatever you like here
}
Define the function outside of either class in a C++ source file, not in the header:
void OtherClass :: Othermethod() {
// call whatever you like here
}
Create a .cpp file:
#include "main.h"
void OtherClass::Othermethod()
{
MyClass m; //ok :)
m.MyMethod(); //also ok.
}
Implementations don't belong in headers anyway.
Some do one .h/.cpp per class:
#ifndef MY_H
#define MY_H
#include "other.h"
class MyClass
{
public:
void MyMethod();
OtherClass test;
}
#endif // MY_H
#ifndef OTHER_H
#define OTHER_H
class OtherClass
{
public:
void Othermethod();
}
#endif // OTHER_H
#include "my.h"
void MyClass::MyMethod() { }
#include "other.h"
#include "my.h"
void OtherClass::OtherMethod)()
{
// (ab)using MyClass...
}
If you're using only Visual Studio, you could use #pragma once
instead of #ifndef xx_h #define xx_h #endif // xx_h
.
EDIT: as the comment says, and also the related Wikipedia page, #pragma once
is also supported (at least) by GCC.
UPDATE: About the updated question, unrelated to #include, but more about passing objects around...
MyClass already has an embedded instance of OtherClass, test
. So, in MyMethod, it's probably more like:
void MyClass::MyMethod()
{
test.OtherMethod();
}
And if OtherMethod needs to access the MyClass instance, pass this instance to OtherMethod either as a reference, or a pointer:
class OtherClass { public: void OtherMethod(MyClass &parent); }
void MyClass::MyMethod() { test.OtherMethod(*this); }
void OtherClass::OtherMethod(MyClass &parent)
{
parent.AnotherMethod();
}
class OtherClass { public: void OtherMethod(MyClass *parent); }
void MyClass::MyMethod() { test.OtherMethod(this); }
void OtherClass::OtherMethod(MyClass *parent)
{
if (parent == NULL) return; // or any other kind of assert
parent->AnotherMethod();
}