2018年5月1日 星期二

Some c++ usage

virtual function

class A{
void foo(){ puts("foo_A"); }
}
class B : A{
void foo() { puts("foo_B"); }
}
B b;
A *p;
p = &b;
p.foo();

expected result : foo_A

class A{
virtual void foo(){ puts("foo_A"); }
}
class B : A{
virtual void foo() override{ puts("foo_B"); }
}
B b;
A *p;
p = &b;
p.foo();
expected result : foo_B

reference

virtual function - abstract class

class C{
virtual void haha() = 0;
}
C c; // error, abstract class can't create instance
class D : C{
virtual void haha() override{ puts("foo_B"); }
}

reference

const after function

 void foo() const

means : foo函式不能修改class內的data member

reference