开发者

Overriding in C++

开发者 https://www.devze.com 2022-12-19 19:07 出处:网络
class base { public: int foo(); int foo(int a); int foo(char* b); int doSomething(int); } class derived : public base
class base {  
    public: 
        int foo();  
        int foo(int a);  
        int foo(char* b);    
        int doSomething(int);    
 }

 class derived : public base
  { 
  public: 
     int doSomething(int b); 
  }

 int derived::doSomething( int b) 
   {
     base::doSomething(b);  
       //Make Something else 
   }

 int main() 
 { 
     derived d= new derived();  
     d->foo();
 }

now开发者_Go百科 in the foo method (any of them) i want to call the more specific doSomething. if i instance a derived class i want the doSomething of the derived class, and if i instance a base class i want the doSomething of the base class, in spite of i'm calling from the foo method implemented in the base class.

int base::foo()
{
 //do something
 makeSomething(5);
}


In your base class, make the doSomething method virtual:

public:

virtual int doSomething(int);

Then you can:

Base* deriv = new Derived();

Base* base  = new Base();

deriv->doSomething();
base->doSomething();

And enjoy!


That is what virtual functions are for:

struct A {
    virtual ~A() {}
    virtual void f() {}
};

struct B : A {
    void f() {}
};

// ...
A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f

The C++ FAQ lite covers some details, but can't substitute a good introductory book.


I would propose this example as to illustrate difference between use of virtual or non-use

struct A {
    virtual ~A() {}
    virtual void f() {}
    void g() {}
};

struct B : A {
    void f() {}
    void g() {}
};

A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f
b->g(); // calls A::g
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号