Path: csiph.com!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: How to assign an object to another in it method? Date: Thu, 13 Jul 2017 21:17:57 -0400 Organization: Aioe.org NNTP Server Lines: 79 Message-ID: References: <46334961-cc18-491f-828c-32e7401c7832@googlegroups.com> NNTP-Posting-Host: PBuS014lhzVyHjLbXmo/ZQ.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.2.1 Content-Language: en-US X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:36922 On 7/13/2017 1:19 PM, Andreas Leitgeb wrote: > Jerry Stuckle wrote: >> On 7/13/2017 6:08 AM, Andreas Leitgeb wrote: >>> I brought up the problem(imho) of overriding methods with >>> changed default values for arguments, which in C++ are static >>> type matter (non-polymorphic). >> Incorrect. Methods with default values are also polymorphic. > > #include > > struct A { virtual void foo(int i = 42) { printf("A: %d\n", i); } }; > struct B : public A { void foo(int i = 54) { printf("B: %d\n", i); } }; > > int main() { > A a; a.foo(); > B b; b.foo(); > A *pa = &a; pa->foo(); > pa = &b; pa->foo(); > } > > Compiling and running it yields: > A: 42 > B: 54 > A: 42 > B: 42 > > The last one polymorphically(because of the 'virtual') calls B::foo(int), > but passss it A::foo's default value, as the pointer is A-typed. > > So, I still consider my claim as correct. You are correct that even virtual call change behavior depending on type of the pointer when default values are applied. I would code the example a bit different: #include using namespace std; class P { public: void virtual foo(int v = 123) { cout << v << endl; } }; class C : public P { public: void virtual foo(int v = 456) { P::foo(v); } void virtual bar() { cout << "Hi" << endl; } }; int main() { // old code P *o1 = new C(); o1->foo(); // new code C *o2 = new C(); o2->bar(); o2->foo(); // return 0; } But it shows the same thing. P *o1 = new C(); vs C *o2 = new C(); changes the behavior of the foo call. Aka non-polymorphic behavior for a virtual method. But: - you would get the same effect without default values for non-virtual methods - how do you know that the method is virtual without noticing the default values? Arne