Overriding in C++
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
精彩评论