Virtual functions and polymorphism - c++

Suppose I have this:
class A
{
public:
virtual int hello(A a);
};
class B : public A
{
public:
int hello(B b){ bla bla };
};
So, A it's an abstract class.
1)In the class B, I'm defining a method that its suppose overrides the A class. But the parameter it's slightly different. I'm not sure about this, is this correct? Maybe because of polymorphism, this is ok but its rather confusing.
2) If I do: A a = new B;, and then a.hello(lol); if "lol" it's not of type B, then it would give compile error?, and if it's of type A from another class C (class C : public A), what would happend?
I'm confused about the overriding and virtual thing.. all examples I found work with methods without parameters.
Any answer, link, or whatever it's appreciated.
thanks
pd: sorry for my english

Your class B doesn't override the member function in A, it overloads it. Or tries to anyway, see the bit about hiding later.
Overriding is when a derived class defines its own version of a virtual member function from a base class. Overloading is when you define different functions with the same name.
When a virtual call is made on a pointer or reference that has the type of the base class, it will only "consider" overrides in the derived class, not overloads. This is essential - for an instance of B to be treated by callers as though it does everything an A can do (which is the point of dynamic polymorphism and virtual functions), its hello function needs to be able to take any object of type A. A hello function which only takes objects of type B, rather than any A, is more restrictive. It can't play the role of A's hello function, so it's not an override.
If you experiment a bit with calling hello on A and B, passing objects of type A or B, you should be able to see the difference. A has a function taking an A (which you haven't defined, so if you call it then your program will fail to link, but you can fix that). B has a function taking a B. They happen to have the same name, and of course since B derives from A, you can pass a B to the function taking an A. But B's function doesn't act as an override in virtual calls.
It is possible to call A's function on a B object, but only via a reference or pointer to A. A feature of C++ is that the definition of hello in B hides the definition in A. If overloading is what you want, it's possible to un-hide the base class function by adding using A::hello; to class B. If overriding is what you want, you have to define a function taking the same parameters. For example:
#include <iostream>
class A
{
public:
virtual int hello(A a) {std::cout << "A\n"; }
virtual int foo(int i) { std::cout << "A::Foo " << i << "\n"; }
};
class B : public A
{
public:
using A::hello;
// here's an overload
int hello(B b){ std::cout << "B\n"; };
// here's an override:
virtual int foo(int i) { std::cout << "B::Foo " << i << "\n"; }
};
int main() {
A a;
B b;
a.hello(a); // calls the function exactly as defined in A
a.hello(b); // B "is an" A, so this is allowed and slices the parameter
b.hello(a); // OK, but only because of `using`
b.hello(b); // calls the function exactly as defined in B
A &ab = b; // a reference to a B object, but as an A
ab.hello(a); // calls the function in A
ab.hello(b); // *also* calls the function in A, proving B has not overridden it
a.foo(1); // calls the function in A
b.foo(2); // calls the function in B
ab.foo(3); // calls the function in B, because it is overridden
}
Output:
A
A
A
B
A
A
A::Foo 1
B::Foo 2
B::Foo 3
If you take away the using A::hello; line from B, then the call b.hello(a); fails to compile:
error: no matching function for call to `B::hello(A&)'
note: candidates are: int B::hello(B)

A bunch of good answers telling you WHAT happens, I thought I'd jump in with WHY.
There's this thing called the Liskov Substitution Principle, which says that the function in the subclass has to work under the same preconditions and postconditions as the base class. In this case, the function has to be able to operate on any object of type A. Note that because of the inheritance relationships, every B is-a A, but not every A is-a B. So to replace the base method, the new function in the derived class can weaken the preconditions or strengthed the postconditions, but not strengthen preconditions or weaken postconditions.
Your attempt to override strengthens the precondition, it accepts Bs, not all As.
Note that covariance IS allowed on return types. If your base class returned A, then it guarantees that the return value is-a A. The base class could then return a B, because every B is-a A.
But for input parameters, only contravariance meets the theoretical requirements of the LSP, and in/out parameters are invariants. In C++ in particular, all parameter types are invariant for the purposes of overloading.

First, A is not an abstract class in your code. It must have at least one pure virtual function to be abstract.
different parameters means completely different method, even though the name is the same. Think of it as a different name. That's why it's called "signature". If A would be an abstract class, this code would not compile at all.
A::hello() will be called. No problem with that, and parameter must be type A, as if there was no inheritance.

When you override a method, it redefines what the method will do. You can only override virtual members that are already defined (with their set of parameters). If the type is of A, the method on A will be called. If the type is of B, the method on B will be called even if the variable is typed A but contains an instance of type B.
You can't change the parameter definitions for an overridden method, or else it would cease to be an override.

What you are doing there is overloading not overriding, i.e. it's as if class B is:
class B
{
public:
int hello(A a) {...}
int hello(B b) {...}
};
You have two functions of the same name, but with different signatures, which makes them different functions (just like the standard library has different functions for abs(float) and abs(double) etc.)
If you want to override, then you need to have the same signature, i.e. class B's hello needs to take a parameter of type A. That way, when you call hello on an object of class B, it will use class B's hello rather than class A's.
If you actually want class B's hello to only accept objects of type B then what you have is fine, although you probably want to make class A's hello non-virtual as you are not really wanting to override it -- you are defining a new function with new parameters and new behaviour.

Thansk for the answers, but I have to clarify some things to get my final answer.
Suppose I have the A class exactly how I defined it in the original question. And I add another method:
class A {
...
int yeah();
}
Then I define class B as the following:
class B : public A {
int hello(A a);
};
And another class C analogous to B.
What I know because I'm the programmer, it's that the hello methods of B and C are gonna have obviously A type objects as parameters, but instances of the same class.
In example:
B b;
b.hello(some_other_b_instance);
or
C c;
c.hello(some_other_c_instance);
The problem is that in each hello function of the classes B and C, I want to do particular things with atributes of the particular class B or C. And because of the parameter is of type A, I cannot use them.
What I would need it's a kind of inverse polymorphysm, but its wrong because by definition I can send a C instance to B hello class, but I know it's not gonna happend.
I hope you get the idea of the code... A clase is abstract, and the real work makes sense in the particular clases B and C, each one do the work in their particular way to make the yeah function work. But B and C need to access their members to do the hello work correctly.

Related

Function overloading and virtual method table [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the slicing problem in C++?
I've got a simple code as a example of polymorphism and inheritance
class A
{
public:
int fieldInA;
void virtual overloadedFunc()
{
printf("You are in A\n");
}
};
class B : public A
{
public:
int fieldInB;
void overloadedFunc()
{
printf("You are in B\n");
}
};
void DoSmth(A* a)
{
a->overloadedFunc();
}
void DoSmthElse(A a)
{
a.overloadedFunc();
}
int _tmain(int argc, _TCHAR* argv[])
{
B *b1 = new B();
B b2;
//Breakpoint here
DoSmth(b1);
DoSmthElse(b2);
scanf("%*s");
return 0;
}
When I stop in breakpoint, the values of _vfptr[0] of b1 and _vfptr[0] of b2 are the same (SomeAddr(B::overloadedFunc(void))).
After passing b1 as parameter in DoSmth(), _vfptr[0] of local variable a is still someAddr(B::overloadedFunc(void)), but _vfptr[0] of a in DoSmthElse is now someAddr(A::overloadedFunc(void)). I'm sure this is some my misunderstaning of function overloading concept, but I couldn't understand, why in first case I saw "You are in B" and in second "You are in A". The same with A *b1 = new B(); DoSmth(b1); // You are in B, why?
First off, you need to get your terminology right! You didn't overload any functions, you overrode them:
Overloading means that you have the same function name with different types of arguments. Choosing the correct overload is a compile-time operation.
Overriding means that you have class hierarchy with a polymorphic (in C++ virtual) function and you replace the function being called with a function applicable to object of a more specialized class. You override the original meaning. Choosing the correct override is a run-time operation, in C++ using something similar to a virtual function table.
The terms are confusing enough and to make things worse, these even interact: At compile time the correct overload is chosen which way end up calling virtual function which may, thus, be overridden. Also, overrides a derived class may hide overloads otherwise inherited from the base class. All this may make no sense if you can't get the terms straight, though!
Now, for your actual problem, when you call DoSmthElse() you pass your object b2 by value to a function taking an object of type A. This creates an object of type A by copying the A subobject of your B object. But since B is derived from A, not all of B gets represented, i.e., the A object you see in DoSmthElse() doesn't behave like a B object but like an A object. After all, it is an A object and not a B! This process is typically called slicing: you slice off the parts of the B object which made it special.
To obtain polymorphic behaviour you need to call virtual functions on a pointer or reference to the base class, not an instance of a base class. When you call this function
void DoSmthElse(A a)
you passed an instance of B. This is pass by value and so the argument is a sliced copy of your B instance that you pass to it. Essentially this means that all of the properties of B that are common to A are preserved in this copy and all of the properties of B that are specific to B and not to A are lost. Because of this, object within DoSmthElse() that the function overloadedFunc() is called on is now exclusively of type A (and no longer of type B) and so of course A::overloadedFunc() is called.
In the first case with DoSmth when the argument is of type pointer to base class, the polymorphic behaviour is obtained as you would expect - the B* argument gets passed to the function and a copy of this pointer is made that is now of type A*. Although the copy has been cast to an A*, the object pointed to is still of type B. Because the object pointed to is of type B the fact that it is accessed via a pointer to it's base class, ensures that the function B::overloadedFunc() is actually called when the line
a->overloadedFunc();
is executed, because the virtual function overloadFunc() is overridden by class B. Had class B not implemented it's own distinct version of the base class virtual function (i.e. Class B overrides the class A functionality) then the base class version would have been called instead.

Virtual unnecessary for protected functions

Say class B derives from class A. That both declare f(). f is protected. Hence f will only be called inside A and inside B. Does f() need to be declared virtual?
Or rather: say C derives from B derives from A. B and A declare protected non-virtual f(). Will a call to f() in C and B resolve to B::f() and in A to A::f()?
In that case, should we always avoid virtual for protected members to have static resolution? Is this done automatically? Thanks!
As long as the call to f() is done in a function derived from A (and not overloaded/reimplemented in B or C), the this pointer resolves to A* and therefore A::f() is called. So no, you still need a virtual function in this case.
Declaring your protected method virtual is necessary when you want polymorphic behaviour (an example to this is the Template Method pattern), and is to be avoided when you don't. However, in the latter case you should not shadow the function with another function having the same signature in the subclass, otherwise you get puzzling behaviour (like the one you describe in your 2nd paragraph) which opens up the possibility for subtle bugs.
I am a bit rusty on my C++ but I would say that "static resolution" would only be guaranteed when you declare the method private and thus you need virtual together with protected in your scenario...
So:
class A {
public:
void f() { std::cout << "A::f\n"; }
};
class B : public A {
public:
void f() { std::cout << "B::f\n"; }
};
As long as the compiler knows that an object is actually a B, it will call f() in B. But, this is not always the case:
void callF(A* a)
{
a->f();
}
B b;
callF(&b); // prints A::f
If you want functions like callF to call the correct f() function, make it virtual. Generally, you make functions virtual if it makes sense to override them in a descendant class. This is often the case for protected functions.

What will happen in this situation?

Say I have base class A. it has method
void foo(A* a);
It also has method
void foo(B* b);
B inherits from A.
Say I now have a B instance but it is an A* ex:
A* a = new B();
If I were to call
someA.foo(a);
Would this call the A* implementation or B* implementation of the method?
I'm providing an A* to the method, but what that object actually is is a B().
Thanks
Function overloads are selected based on the static type of the passed parameter. The static type of a is A*, only its dynamic type is B. Go figure.
Well, two things will happen. First of all the determination of which function to call:
A* a = new B();
foo(a);
Here you pass a variable of type A* (C++ = static typed, remember) to foo, this will as usual call foo(A* a), nothing different from any other function overloading. If you were to call foo(new B()) it would use the implicit type B* and end up calling foo(B* b). Nothing new here, plain old function overloading. Note that only when foo(B*) is not present it will fall back to a more generic version because of inheritance.
Now in your example we come to the calling of this function:
void foo(A* a)
{
a->foo();
}
Well, again, standard C++ calling conventions apply, including polymorphism. This means if you have declared foo as virtual the vtable will be constructed in such a way that the foo method of B will be called for your example (as the object is created as type B). If A::foo() is not declared as virtual, the method of A itself will be called.
Because A::foo(A*) and B::foo(B*) have different signatures (types of their arguments), the compiler treats them as totally different functions. If instead of calling both methods foo() you had called one A::bar(A*) and another B::baz(B*), you would get identical behavior.
foo(A*) is a method of all objects of type A, and all objects of type B are also objects of type A because B is derived from A. So foo() is indeed a method of the object someA, inherited from the parent A class. This method, the A method, is the one that gets called.
I would expect it to use the foo(A *) method because the static type is A.
But, like someone said, add some logging and try checking which one is being executed.

Why is it allowed to call derived class' private virtual method via pointer of base class?

# include <iostream>
using namespace std;
class A
{
public:
virtual void f()
{
cout << "A::f()" << endl;
}
};
class B:public A
{
private:
virtual void f()
{
cout << "B::f()" << endl;
}
};
int main()
{
A *ptr = new B;
ptr->f();
return 0;
}
This code works correctly and prints B::f(). I know how it works, but why is this code allowed?
Access control is performed at compile time, not runtime. There's no way in general for the call to f() to know the runtime type of the object pointed to by ptr, so there's no check on the derived class's access specifiers. That's why the call is permitted.
As for why class B is permitted to override using a private function at all - I'm not sure. Certainly B violates the interface implied by its inheritance from A, but in general the C++ language doesn't always enforce inheritance of interface, so the fact that it's Just Plain Wrong doesn't mean C++ will stop you.
So I'd guess that there's probably some use case for this class B - substitution still works with dynamic polymorphism, but statically B is not a substitute for A (e.g. there can be templates that call f, that would work with A as argument but not with B as argument). There may be situations where that's exactly what you want. Of course it could just be an unintended consequence of some other consideration.
This code is allowed because f is public in A's interface. A derived class cannot change the interface of a base class. (Overriding a virtual method isn't changing the interface, nor is hiding members of a base, though both can appear to do so.) If a derived class could change a base's interface, it would violate the "is a" relationship.
If the designers of A want to make f inaccessible, then it should be marked protected or private.
Your base class is defining the interface for all the inherited children. I do not see why it should prevent the mentioned access. You can try deriving a class down from 'B' and use the Base interface to call , which would result in an error.
Cheers!
In addition to Steve's answer:
B is publically derived from A. That implies Liskov substitutability
Overriding f to be private seems to violate that principle, but actually it does not necessarily - you can still use B as an A without the code getting in the way, so if the private implementation of f is still okay for B, no issues
You might want to use this pattern is B should be Liskov substitutable for A, but B is also the root of another hierachy that is not really related (in Liskov-substitutable fashion) to A, where f is no longer part of the public interface. In other words, a class C derived from B, used through a pointer-to-B, would hide f.
However, this is actually quite unlikely, and it would probably have been a better idea to derive B from A privately or protected
Function access control check happens in later stage of a c++ function call.
The order in high level would be like name lookup, template argument deduction(if any), overload resolution, then access control(public/protect/private) check.
But in your snippet, you were using a pointer to base class and function f() in base class is indeed public, that's as far as compiler can see at compiler time, so compiler will certain let your snippet pass.
A *ptr = new B;
ptr->f();
But all those above are happens at compile time so they are really static. While virtual function call often powered by vtable & vpointer are dynamic stuff which happens at runtime, so virtual function call is orthogonal to access control(virtual function call happens after access control),that's why the call to f() actually ended B::f() regardless is access control is private.
But if you try to use
B* ptr = new B;
ptr->f()
This will not pass despite the vpointer & vtable, compiler will not allow it to compile at compile time.
But if you try:
B* ptr = new B;
((static_cast<A*>(ptr))->f();
This would work just fine.
Pretty much like in Java, in C++ you can increase the visibility of methods but not decrease it.

Why does a virtual function get hidden?

I have the following classes:
class A {
public:
virtual void f() {}
};
class B : public A{
public:
void f(int x) {}
};
If I say
B *b = new B();
b->f();
the compiler says error C2660: 'B::f' : function does not take 0 arguments.
Shouldn't the function in B overload it, since it is a virtual function? Do virtual functions get hidden like this?
EDIT: I indeed meant to inherit B from A, which shows the same behaviour.
Assuming you intended B to derive from A:
f(int) and f() are different signatures, hence different functions.
You can override a virtual function with a function that has a compatible signature, which means either an identical signature, or one in which the return type is "more specific" (this is covariance).
Otherwise, your derived class function hides the virtual function, just like any other case where a derived class declares functions with the same name as base class functions. You can put using A::f; in class B to unhide the name
Alternatively you can call it as (static_cast<A*>(b))->f();, or as b->A::f();. The difference is that if B actually does override f(), then the former calls the override, whereas the latter calls the function in A regardless.
Class B does not derive from A so no function F() exists. You probably meant:
class A {
public:
virtual void f() {}
};
class B : public A {
public:
void f(int x) {}
};
Edit: I missed the actual function hiding. See Steve Jessop answer for more thorough explanation.
No, and yes, respectively. If you want the overloading behaviour, you need to say
using A::f;
in B.
B does not derive from A, the correct declaration is:
class B : public A
When the compiler has more than one way to resolve a symbol, it has to choose which one has precedence unless the code tells it otherwise. What you are expecting is the overloading to take precedence over the overriding. (over, over, over, aaaaack! Sorry, got 'over'whelmed).
This example has B inheriting a virtual method in which the subclass provides an overloaded version. Overloads are for methods in the same class using the same method name but different signatures. Since B is a subclass of A, it is overriding f(), which means it cannot also be an overload at the same time. This is why it is being hidden.
For class A, declaring method
virtual void f() {}
as virtual means that method will be resolved using a certain set of rules that are not consistent with your declaration of b.
B *b = new B();
By creating 'b' as an instance of "B", the compiler has no need to use the virtual nature of the method of the same name in "A".
If you had declared 'b' like this
B *b = new A();
then the call b->f(); would indeed refer to the method in A by making use of the virtual resolution.
It seems that it is exist rather similar question with answer in Biern Stroustrup's FAQ: http://www.stroustrup.com/bs_faq2.html#overloadderived
As he said:
"In C++, there is no overloading across scopes"
but if you want
"That's easily done using a using-declaration"