I'm Java programmer and I'm new to C++ Programming. In java we have to write all classes in separate files and all method's definitions are right inside the class. But now in C++ I'm wonder that why C++ allow programmers to write method's definition outside a class. Is there any way to write C++ programs like Java?
You can write the code for your classes within the header file if you like. This makes the header file in C++ similar to the java file in java.
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
#include "OtherClass.h"
class MyClass {
public:
MyClass() { _otherClass=0; }
void set(OtherClass* oc) { _otherClass = oc; );
OtherClass* get(void) { return _otherClass; };
private:
OtherClass* _otherClass;
};
#endif
But you can also split the header and the code into two files in C++. This allows you to separate the definition and declaration of the methods and reduces compile time header dependencies.
Note that in the example above, any class which includes MyClass.h will automatically include OtherClass.h whether it needs it or not, and changes to OtherClass.h will require recompiling of all clients of MyClass.h.
However in the separated example below, there is a forward declaration of OtherClass.h (this is possible because it is only used as a pointer), and the actual OtherClass.h is only included in the cpp file. Now changes to OtherClass.h will only force recompile of MyClass.cpp, and not clients of MyClass.h (unless they also include OtherClass.h),
It also means that you can make a change to MyClass::get() and you will only need to recompile MyClass.cpp, not all clients of MyClass
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class OtherClass;
class MyClass {
public:
MyClass();
void set(OtherClass* oc);
OtherClass* get(void);
private:
OtherClass* _otherClass;
};
#endif
#include "MyClass.h"
#include "OtherClass.h"
MyClass::MyClass() : _otherClass(0) {}
MyClass::set(OtherClass* oc) { _otherClass=oc; }
OtherClass* MyClass::get() { return _otherClass; };