Override and Overload Methods

Can I overload or override methods just using a different return value? is a virtual question in this case?

eg:

class A{ virtual int Foo(); // is this scenario possible with/without the keyword virtual } class B : public A { virtual double Foo(); } A* Base = new B(); int i = Base->Foo(); // will this just convert double to int ? 

and regarding overload:

 class A{ virtual int Foo(); virtual float Foo(); // is this possible ? int Goo(); float Goo(); // or maybe this ? } Class B{ double Foo(); } 

thanks

+1
source share
8 answers

The return type of the function is not part of its signature, so it cannot be overloaded.

+8
source

The return value is not part of the function signature, how will the compiler now, which version should I choose?

If you remove virtual from Foo in the first example, it will work and will call Base::Foo .

+4
source

No, you cannot do this.

What you can do with the overriden method is to return a pointer / reference to a type that is a descendant of the type returned by the parent method.

Example:

 struct VA {} struct VB : struct VA {} class A { public: virtual VA * get(); } class B { public: virtual VB * get(); } 
+4
source

Overloading with a change in the return value is not possible.

consider this:

 Base->Foo(); 

called without assigning a return value, then the compiler cannot infer which method to call.

Keyword

virtual used to create VTable and thereby prove dynamic polymorphism. This does not affect overload methods.

+1
source

The return value is not part of the signature, unfortunately, therefore not.

+1
source

No, there are some similar things that you can do, for example, for example. templatize the return value (possibly with specializations) and specify the type of template when invoked, for example.

 template<T> T Foo() { return 0; } template<> double Foo<double>() { return 3.14; } int i = Foo<int>(); // 0 double d = Foo<double>(); //3.14 
+1
source

As for redefinition, this refers to the class of arancharism and it is possible to achieve polymorphism at run time.

 class Abstract { public : virtual Abstract* Clone() const = 0; }; class Concrete1 : public Abstract { public : Concrete1* Clone() const { return new Concrete1(*this); } }; class Concrete2 : public Abstract { public : Concrete2* Clone() const { return new Concrete2(*this); } }; 

Area overloading is not possible according to the C ++ standard.

+1
source

When using VC ++, you get the error type "overloaded method only in the inverse type." This is because method / function signatures do not include a return type. I guess this is due to the ambiguity that this can cause if the return value is not assigned to anything. eg,

int iMyvar = object.method (); // obviously, what type should be returned

Contrast with: -

object.method (); // what overload will the compiler cause if the return type was part of the signature? Ambiguos.

+1
source

Source: https://habr.com/ru/post/1308084/


All Articles