0

Is there any way to reference classes/methods in one file where the order of them wouldn't matter? My question might look weird but I will present example: I must include all code in one source file (I know it's really unhandy) for entry so for example:

class One{
public:
    float methodOne(){
        return multiply(10, 20);
    }
};

float multiply(float a, float b){ return a * b; }

to reference multiply I would need to move it over the method that reference it but with more classes and methods it starts to become impossible so is there any other way to do this than moving methods over?

*edit i forgot to add the main problem that the methods are using classes which causes the mess

2 Answers2

1

you can add function prototype on top of program or in header file

float multiply(float, float);
class One{
  public:
     float methodOne(){
        return multiply(10, 20);
     }
};

float multiply(float a, float b){ 
return a * b; 
}

then you can define it anywhere(below or above class)

Mesar ali
  • 1,832
  • 2
  • 16
  • 18
  • i forgot to add that my methods use my classes inside them and that causes the main problem . Would this solution apply if in parameters there would be class defined below? – Jakub Gonera Apr 22 '18 at 11:23
  • Class is kind of a dynamic type, which you can't use before it's definition, So I don't think it will work – Mesar ali Apr 22 '18 at 11:26
  • In case if class member functions, you can define them outside class, using scope resolution operator(::) – Mesar ali Apr 22 '18 at 11:32
0

In a small program, I would create a header file which declares all the functions and and classes. All the functions (class methods and independent methods) can be implemented (defined) in a .cpp file in any order. Just need to include the header file in the .cpp file. In a large project, it is better to create a pair of .h and .cpp files for each class. The independent functions can be implemented in a separate pair of .h and .cpp files. With this approach, you wouldn't need to care about the order of function definitions. Whenever you call a function, make sure to include corresponding .h file.

AVD
  • 41
  • 1
  • 7