c++ - Question on Virtual and default arguments -


i wanted have confirmation following things:

virtual mechanism:

i f have base class , has virtual method, in derived class generally, not include virtual statement in function declaration. virtual mean when included @ dervied class definition.

class { public:  virtual void something(); }  class b:public { public: virtual void something(); } 

does, mean want override method somethign in classes derive class b?

also, question is,

i have class a, derived 3 different classes.now, there virtual method anything(), in base class a.

now, if add new default argument method in base class, a::anything(), need add in 3 classes right.

my pick answers:

  1. if method virtual in base class redefined in derived class virtual might mean shall overridden in corresponding derived classes uses class base class.
  2. yes.if not overriding not have meaning.

pls let me know if feel(above 2) correct.

thanks, pavan moanr.

the virtual keyword can omitted on override in derived classes. if overridden function in base class virtual, override assumed virtual well.

this covered in question: in c++, function automatically virtual if overrides virtual function?


your second question default values , virtual functions. basically, each override can have different default value. however, not expect do, advice is: do not mix default values , virtual functions.

whether base class function defaulted or not, totally independent whether derived class function defaulted.

the basic idea static type used find default value, if defined. virtual functions, dynamic type used find called function.

so when dynamic , static type don't match, unexpected results follow.

e.g.

#include <iostream>  class { public:   virtual void foo(int n = 1) { std::cout << "a::foo(" << n << ")" << std::endl; } };  class b : public { public:   virtual void foo(int n = 2) { std::cout << "b::foo(" << n << ")" << std::endl; } };  int main() {   a;   b b;    a.foo(); // prints "a::foo(1)";   b.foo(); // prints "b::foo(2)";    a& ref = b;   ref.foo(); // prints "b::foo(1)"; } 

if overrides share same default, solution define additional function in base class nothing call virtual function default argument. is:

class { public:    void defaultfoo() { foo(1); }    virtual void foo(int n) { .... } }; 

if overrides have different defaults, have 2 options:

  • make defaultfoo() virtual well, might result in unexpected results if derived class overload 1 not other.
  • do not use defaults, explicitly state used value in each call.

i prefer latter.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -