Jump to content

What is the difference between?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
suchi

suchi

    Newbie

  • Members
  • Pip
  • 1 posts
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.

#2
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts

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
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
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.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog