should it be member function or not

F

free2cric

Hi,
Just posting a sample progam.
class asd's member function calls function b which is not a member
function and passes it a class's variable as parameter . Should the
called function be a member of class? logically we can call it. but
what do u think what is a good practice??? thanks cric.

int b(int t)
{
return (t*t)
}

class asd
{
private:
int type;
int v;

public:
asd() { type = 10; }
void a();
};

void asd::a()
{
v= 10 * b(type);
}
 
S

shivank

it depends.
seeing the code above, I will say why to have the function b at all. ;)
But, see if b takes class asd object as argument and only operates on
it, then basically b is providing some operation for asd object only,
so better it should be member function of the class itself. But if it
operates on some generalised data type say int, which can be a data
member of any class, and also the calculation in b are big that it
cannot be part of the code everywhere it is called then b should be an
independent function.

in your code above you are not passing object of asd to b, but passing
only an integer !

-- Regards,
Shivank
 
K

Karl Heinz Buchegger

Hi,
Just posting a sample progam.
class asd's member function calls function b which is not a member
function and passes it a class's variable as parameter . Should the
called function be a member of class?

That cannot be answered without knowing more of your actual problem domain.
If something should be a member function of not depends mostly how tightly
the functionality of that function is coupled to the class. In other
words: Does it make sense to have that function standalone or not. Can
the function be used without that class or is it so tightly coupled that
it doesn't make sense to have it standalone.
logically we can call it. but
what do u think what is a good practice??? thanks cric.

In your example:
int b(int t)
{
return (t*t)
}

This is a function that returns twice the number given to it. Such
a function makes sense for it alone, it doesn't depend on anything
of the caller.

int main()
{
int i;

std::cout << "2-times " << i << " makes " << b(i) << std::endl;
}

is just a valid usage of that function as is your usage of calling from
a class member function.

Thus in this specific case I would say: that function should be a
standalone function.
 
K

Karl Heinz Buchegger

Howard said:
Oopsy! Somebody needs to check their math! :)

Aeeeehm, yes.

( My usual Email signature contains:
2 + 2 = 5, for very large values of 2)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,203
Messages
2,571,059
Members
47,668
Latest member
SamiraShac

Latest Threads

Top