2008/11/02

(C++)virtual與pure virtual

virtual function
如果子class 有override virtual function,就會跳到下面的class做,base class不做事
如果子class 沒有override virtual function,base class就要做事
Ex:
class B{
public:
virtual void f(){
cout<< "BBB";
}
};
class A:public B{
public:
void f(){
cout <<"AAA";
}
};
int main(){
B *b = new A();
b->f(); // 印出AAA
return 0;
}

Ex:
class B{
public:
virtual void f(){
cout<< "BBB";
}
};
class A:public B{
};
int main(){
B *b = new A();
b->f(); // 印出BBB
return 0;
}

如果Base Class的function不是virtual,則子class的function無法覆蓋。如下例:
Ex:
class B{
public:
     void f(){ // non-virtual
        cout<< "BBB";
    }
};
class A:public B{
public:
   
    void f(){ // cannot override a
non-virtual function
       cout <<"AAA";
    }
};
int main(){
    B *b = new A();
    b->f(); // 印出BBB
    return 0;
}
 


Pure virtual function
base class的Pure virtual function不實做。
子class一定要override pure virtual function

Ex:
class B{
public:
virtual void f() = 0;
};
class A:public B{
public:
void f(){
cout <<"AAA";
}
};
int main(){
B *b = new A();
b->f(); // 印出AAA
return 0;
}

Virtual function: Differences between C++ and Java
C++ Java
Pure Virtual Function vitual void func() = 0; abstarct void func();
Impure Virtual Function vitual void func(); void func();
Non-Virtual Function void func(); final void func();
Hiding Inherited Names Yes No
Prohibiting Inheritance No final class

1 則留言:

Unknown 提到...

如果Base Class的function不是virtual,則子class的function無法覆蓋。如下例:

這是錯的吧?

Buddhism and Software Developer

In today's fast-paced society, we are often surrounded by work, goals, and external pressures. However, the wisdom found in Buddhism off...