Could somebody help me out to point out Difference Between Friend Function and virtual function. I am very much confuse with the definition and use of both also.
What is the difference between?
Started by suchi, Jul 26 2009 06:43 AM
2 replies to this topic
#1
Posted 26 July 2009 - 06:43 AM
|
|
|
#2
Posted 26 July 2009 - 07:39 AM
class A
{
public:
inline A( int data = 0 )
: data_( data )
{
}
inline A( const A& other )
: data_( other.data_ )
{
}
inline A& operator=( const A& other )
{
if ( this != &other )
{
data_ = other.data_;
} // if
return *this;
}
inline virtual ~A( void )
{
}
inline virtual void setData( const int data )
{
data_ = data;
}
private:
int data_;
friend void setData( A& a, const int data );
};
class B
: public A
{
public:
B( int data = 0 )
: A( data )
{
}
inline B( const A& other )
: A( other )
{
}
inline B& operator=( const B& other )
{
if ( this != &other )
{
A::operator=( other );
} // if
return *this;
}
inline ~B( void )
{
}
inline void setData( const int data )
///
/// overridden from class A
/// can not access A's private member data_
///
{
/// data_ = data
///
/// ^ compiler error
/// assert( 0 >= data && data <= 100 );
///
/// ^ here you could check if the data is valid
/// or alter the behavior of setData otherwise
///
A::setData( data );
}
private:
// ...
};
inline void setData( A& a, const int data )
///
/// friend function of class A
/// can access private members of class A
///
{
a.data_ = data;
}
Friend functions or classes have access to private members of the object.
Hope the code above clears it some, theres alot documentation on this if not.
#3
Posted 26 July 2009 - 11:45 AM
A friend function is a function that has access to a class's private members, but is NOT part of the class. A virtual function is a function that is part of a class but will honor polymorphic behavior. Virtual functions will not make sense unless you understand how to do inheritance.


Sign In
Create Account

Back to top









