Friday, July 31, 2009

C++ Using functions that are declared in other class?

Hi!!!





For example I have this:





//a.cpp


#include a.h


a :: a(){...}


int a :: fun() { int x= 123445564343 return x}





//b.cpp


#include b.h


b :: b(){


... //I want call here fun() declared in "a.cpp" and assign the value returned.


}





How can I do that?


Please give me an example.





Thanks!!!

C++ Using functions that are declared in other class?
You cannot employ member methods from other classes unless the class that wants to use them is a child of the first class.
Reply:For the following I assume that the class a is declared in a.h and b is not derived from a.


1) To access a::fun() b.cpp need its definition so you need "#include a.h" in b.cpp.


2) Make sure that fun() is declared public in a.h.


3) Normally a method of a class accesses its members so it must be called on an instance of that class


Ex:


. int i;


. a test;


. i = test.fun();


For the case you are describing, fun() does not use any of a's members so it could be declared static in a.h and then called directly as "i = a::fun()" without creating an instance of a.





I hope this helps you.
Reply:You can't call varibles of one class to another, unless it is a subclass and in some cases if variables are not declared private. You can't use varibles of one class to another, if so, you have to declare them as public and be sure that they have to be out of any class.


No comments:

Post a Comment