Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class implementation in multiple files

Tags:

c++

I am trying to implement a class in different cpp files. I understand it is a legitimate thing to do in C++ if the member functions are independent. However one of the member function uses another member function such as in this case:

In function1.cpp

#include "myclass.h"
void myclass::function1()
{ 
    function2();
}

In function2.cpp

#include "myclass.h"
void myclass::function2()
{
....
}

I will get an error of undefined reference to function2. It doesn't work by adding this pointer either. Do I need to declare it in some way in function1.cpp? Thanks~

The header file includes declaration of both functions. It works when function1 and function 2 are in the same file but not when I separate them. I also believe I've added both cpp in the project. I am using Qt creater btw.

like image 786
Bill Avatar asked Aug 04 '11 10:08

Bill


People also ask

Which file is class implementation?

cpp file, which is called the class implementation file. The file usually has the same name as the class, with the . cpp extension. For example the Time class member functions would be defined in the file Time.

What is the difference between .h and .cpp files?

The short answer is that a . h file contains shared declarations, a . cpp file contains definitions and local declarations. It's important that you understand the difference between declarations and definitions.

What is multiple file compilation?

Multiple File Projects: Most of the time, full programs are not contained in a single file. Many small programs are easy to write in a single file, but larger programs involve separate files containing different modules. Usually, files are separated by related content.


1 Answers

As long as myclass.h contains the definition of the class with the declarations of the member functions, you should be fine. Example:

//MyClass.h
#ifndef XXXXXXXX
#define XXXXXXXX
class MyClass
{
  public:
   void f1();
   void f2();
};
#endif

//MyClass1.cpp
#include "MyClass.h"
void MyClass::f1()
{
};

//MyClass2.cpp
#include "MyClass.h"
void MyClass::f2()
{
     f1(); //OK
}
like image 198
Armen Tsirunyan Avatar answered Oct 05 '22 23:10

Armen Tsirunyan