0

When we write class in c++ we divide class into two part that header file and cpp file. In header file we define class and prototype

Class.h

class A{
public:
void functionName();
};

Then we define what the function actually does in cpp

Class.cpp

#include<iostream>

void A:: functionName(){
 do something;
}

then in main function we do

#include "class.h" 
using namespace std;
int main()
{
  A a;
  a.functionName();
  return 0;
}

Is their a better way to do it?. Somthing similar to java(that's the language i currently work with). I think doing things like this(cpp way) in big projects will be Messy to work with

  • 1
    define "better". C++ is not Java. The C++ build process works in fundamentally different ways. If what you actually wanted to do is use Java then why not just use Java? The last thing you wanna do is write Java in C++… – Michael Kenzel Jan 15 '20 at 10:54
  • 3
    C++20 has modules. – Jarod42 Jan 15 '20 at 10:55
  • You can write all your code in header files. It is considered bad practice though – Raildex Jan 15 '20 at 10:56
  • *"we divide class into two part that header file and cpp file"* - not necessary. You can write all your code in header files. It is considered a good practice. – user7860670 Jan 15 '20 at 10:56
  • 1
    @MichaelKenzel I assume they mean "less duplication" and more "centralised", e.g. both the header and source file need the function signature, and you often need both the header and source file open. Inline functions are sometimes an option, but they have their own limitations and I certainly wouldn't try and write a "big project" using almost only headers. – Fire Lancer Jan 15 '20 at 10:57
  • @Jarod42 Yes, we all hope that modules are going to be great. But C++20 modules will still work very differently from how Java builds work. And C++20 modules are not even out yet. And build system integration for C++20 modules is a yet unsolved problem… – Michael Kenzel Jan 15 '20 at 10:57
  • Of course you can simply use just a function. – KimKulling Jan 15 '20 at 11:07
  • 2
    The biggest **advantage** of separating interface from implementation comes when you work on big projects. It saves you from having to recompile all of your code when you tweak a small implementation detail. – Pete Becker Jan 15 '20 at 14:24

0 Answers0