简体   繁体   中英

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

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 (ie virtual void foo(void) = 0; ).

因为a:foo()不公开。

Several things:

  1. Write foo() and not foo(void) ... the latter is unnecessary and not idiomatic C++ (it is C-like syntax).
  2. Don't write class in a* b_ptr = new b; , since a's type has already been declared.
  3. You should return from a function that doesn't return void (add return 0 ).
  4. Your code never frees b_ptr . It would be better to write std::auto_ptr<a> b_ptr(new b); .
  5. The compile-time type (declared type) of b_ptr is a* while it's runtime type (instantiation/allocation type) is b* . The compiler (and the type system) only know about compile time types, and so checks for access privileges are performed based on compile-time type... hence b_ptr->foo() isn't allowed.
  6. Either use a declared type of b* or make a::foo public to use it in the way you wish.

Make that

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

You can't override a private function. Though I'm not sure how you managed to call b_ptr->foo() anyways since a::foo is private.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM