Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function

Tags:

c++

class a
{
 virtual void foo(void) ;
};

class b : public  a
{
public:
 virtual void foo(void)
  {
  cout<< "class b";
  }
};

int main ( ) 
{
class a *b_ptr = new b ;
b_ptr->foo();
}

please guide me why the b_ptr->foo() will not call the foo() function of the class b?

like image 247
user296113 Avatar asked Mar 18 '10 00:03

user296113


1 Answers

As you've written the code, it won't compile due to access control violations. Since b_ptr is actually of type a * and a::foo is private, the compiler won't allow that.

But make a::foo public and that will correctly call b::foo.

There is also the problem that you have not defined a::foo so your program won't link. You need to either define it or make it pure virtual (i.e virtual void foo(void) = 0;).

like image 51
R Samuel Klatchko Avatar answered Oct 05 '22 15:10

R Samuel Klatchko