Home have classes in separte files access it's other c++
Reply: 2

have classes in separte files access it's other c++

Chris Skan
1#
Chris Skan Published in 2017-12-06 23:09:18Z

Well I have 2 classes in 2 header and 2 cpp files

#class1.h
#ifndef class1_h
#define class1_h
class myclass;
#endif

#class2.h
#ifndef class2_h
#define class2_h
class anotherclass;
#endif

#class1.cpp

class myclass
{
    anotherclass test1;
}

#class2.cpp

class anotherclass
{
    myclass test2;
}

And of course a simple main Well I think it's obvious why this thing wont even compile my question here is how to make it compile?
Having the classes in different files is mandatory..

SoronelHaetir
2#
SoronelHaetir Reply to 2017-12-06 23:26:29Z

If the class definitions (the bodies that is) must be in separate files then the members of the declared type can only be a pointer (or a reference but that is unusual). You would then need a function in the source file where the class is actually defined that returns a pointer-to-instance of the type.

MyClass.h:

#if !defined(MYCLASS_H)
#define MYCLASS_H
class MyClass;
MyClass * CreateMyClass();
#endif

OtherClass.h:

#if !defined(OTHERCLASS_H)
#define OTHERCLASS_H
class OtherClass;
OtherClass * CreateOther();
#endif

myclass.cpp

#include "otherclass.h"
class MyClass
{
OtherClass * ptrOther;
public:
MyClass()
: ptrOther(CreateOther())
{}
};

otherclass.cpp:

#include "myclass.h"
class OtherClass
{
MyClass * ptrMyClass;
public:
OtherClass()
: ptrMyClass(CreateMyClass())
{}
};

Note that doing things this way you would not actually be able to do anything with ptrOther or ptrMyClass ((possibly not even free them correctly), It would be much more typical to place the class definitions in the header and separate out the member definitions (for functions and statics), like the following:

MyClass2.h:

#if !defined(MYCLASS2_H)
#define MYCLASS2_H
#include "OtherClass.h"
class MyClass2
{
OtherClass * ptrOther;
public:
MyClass2();
};
#endif

cMyClass.cpp:

#include "MyClass2.h"
MyClass2::MyClass2()
: ptrOther(CreateOther())
{}
DannyK
3#
DannyK Reply to 2017-12-06 23:27:34Z

Header files define class interfaces. Source code '.cpp' files are using for the implementation. Your source code has the implementation and the class interface.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303537 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO