Hi,
I have a Class A with public function A. A calls another function B.
We usually avoid calling A::A() as 'member function'. We call it
'constructor'. Constructor is special in sense that it returns nothing,
not even void. It does construct instances of class, objects of type A.
I want to let only public functions of class A use B. So i thought of putting
it in private of Class A.
That is fine to have private member functions.
Is this the best way? or simple declaring them as static and keep it
outside of class?
Hard to answer. It depends what you need.
Non-static member functions have passing of one parameter simply displayed
differently. Example Number class:
class Number
{
public:
Number( int n = 0 );
Number& increase();
static Number& addOne( Number& nr );
int value_;
};
Number::Number( int n )
: value_( n )
{ }
Number& Number::increase()
{
++value_;
return *this; // 'this' is technically name of special parameter.
}
Number& Number::addOne( Number& nr )
{
++nr.value_;
return nr;
}
Number& Increase( Number& nr ) // may be static
{
++nr.value_;
return nr;
}
Here the non-static member function Number::increase() does exactly same
thing as do free function Increase( Number& ) and static member function
Number::addOne( Number& ). Member functions may be made private but free
function may me made static and remove any traces of its existence from
class definition. The only problem is that it can not access private or
protected members itself.
Major difference is still the way how the call looks in code:
int main()
{
Number x( 42 );
x.increase(); // non-static member function
Number::addOne( x ); // static member function
Increase( x ); // free function
}
New to C++. So forgive me if it is a silly q.
Not silly at all. It is the most important part of class, what functionality
is exposed to outer world and with what interface. It is design,
it is art. It is the difference between inconvenient + hard to read
and easy to use + simple to read.
I can not suggest what to take since example containing 'A's and 'B's
does not describe the real situation, that is always different.