Virtual function

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 tell me why b_ptr-> foo () will not call the function foo () of class b?

+7
c ++
source share
4 answers

As you wrote the code, it will not compile due to access control violations. Since b_ptr is of type a * and a::foo is private, the compiler will not allow this.

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

There is also a problem that you did not define a::foo so that your program does not bind. You need to either define it or make it pure virtual (i.e. virtual void foo(void) = 0; ).

+17
source share

Because a: foo () is not publicly available.

+3
source share

A few things:

  • Write foo() , not foo(void) ... the latter is not needed, not idiomatic C ++ (this is a C type syntax).
  • Do not write class in a* b_ptr = new b; since the type is already declared.
  • You must return from a function that does not return void (add return 0 ).
  • Your code never frees b_ptr . Better to write std::auto_ptr<a> b_ptr(new b); .
  • The compile-time type (declared type) of b_ptr is a* , while its execution type (instance / placement type) is b* . The compiler (and type system) only knows about compile-time types, and therefore access control checks are based on the compile-time type ... therefore, b_ptr->foo() not allowed.
  • Use the declared type b* or make a::foo publicly available to use it the way you want.
0
source share

Do it

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

You cannot override a private function. Although I'm not sure how you managed to call b_ptr->foo() , since a::foo is private.

-one
source share

All Articles