Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access member function of another .cpp within same source file?

Tags:

c++

class

I am working in Visual C++. I have two .cpp files in the same source file. How can I access another class (.cpp) function in this main .cpp?

like image 948
Rajakumar Avatar asked Aug 20 '09 04:08

Rajakumar


2 Answers

You should define your class in a .h file, and implement it in a .cpp file. Then, include your .h file wherever you want to use your class.

For example

file use_me.h

#include <iostream>
class Use_me{

   public: void echo(char c);

};

file use_me.cpp

#include "use_me.h" //use_me.h must be placed in the same directory as use_me.cpp

void Use_me::echo(char c){std::cout<<c<<std::endl;}

main.cpp

#include "use_me.h"//use_me.h must be in the same directory as main.cpp
    int main(){
       char c = 1;

       Use_me use;
       use.echo(c);

       return 0;

    }
like image 129
Tom Avatar answered Oct 20 '22 15:10

Tom


Without creating header files. Use extern modifier.

a.cpp

extern int sum (int a, int b);

int main()
{
    int z = sum (2, 3);
    return 0;
}

b.cpp

int sum(int a, int b)
{
    return a + b;
}
like image 41
Vladimir Obrizan Avatar answered Oct 20 '22 16:10

Vladimir Obrizan