Pregunta

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?

¿Fue útil?

Solución

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.

MyClass.h

#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

MyClass.h

#ifndef _MYCLASS_H_
#define _MYCLASS_H_

class OtherClass;

class MyClass {
public:
    MyClass();

    void set(OtherClass* oc);
    OtherClass* get(void);

private:
   OtherClass* _otherClass;
};
#endif

MyClass.cpp

#include "MyClass.h"
#include "OtherClass.h"

MyClass::MyClass() : _otherClass(0) {}

MyClass::set(OtherClass* oc) { _otherClass=oc; }

OtherClass* MyClass::get() { return _otherClass; };

Otros consejos

But now in C++ I'm wonder that why C++ allow programmers to write method's definition outside a class.

Two major reasons are compilation times and separating the implementation from the interface. This is covered in more detail in In C++ why have header files and cpp files?

Is there any way to write C++ programs like Java?

You could write your entire implementation in header files, but you shouldn't. When writing code in any language, you should follow that language's idioms as this makes it easier to read and to maintain.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top