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.
Related
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.
I have a theoretical question about C++. It was part of the final exam at my university and I want to know why the method f of class B is called, while it should be derived by the base class A. Since it is not virtual shouldn't the A::f() be called?
#include <iostream.h>
#include <stdlib.h>
class A{
public:int f(int x){
cout<< x << " ";
}
};
class B:public A{
public:int f(int y){
A::f(y+1);
}
};
void g(A a, B b) {
a.f(3);
b.f(3);
}
int main()
{
B p;
B q;
g(p,q);
system("PAUSE");
return 0;
}
// result is 3 4
The static type if b in g() is B, thus there is no need for virtual here - the compiler can know [at compile time] you want to invoke B::f(), and that is exactly what he is doing. In here, the class B redefined A's f(), and hides it, so invoking f() from a variable whose static type is B results in invoking B::f()
Note that the virtual keyword allows you to use overriding methods where the static type is the parent's type.
The method g takes two arguments, of type A and B repsectively. Since these are no pointer or reference types, dynamic binding does not apply. The compiler knows at compile time the actual type of the objects, and does a static method call.
virtual methods only apply if you have pointers or references!
The function int f(int) in class B "hides" the function with the same name and signature in its base class.
So, when you call b.f(3);, and the variable b has type B, you are calling B::f.
Virtual functions are only needed if you want b.f(3) to call B::f in cases where the type of the variable b is A&, but the object it refers to has runtime type B. In that situation, the function called would be B::f if A::f is virtual, but A::f is called if non-virtual.
Virtual function calls take the runtime type of objects into account even if they're used via a pointer or reference to a base class. But B b; b.f(3) is a call to B::f regardless of whether A::f even exists, never mind whether it's virtual or non-virtual.
There are 2 things happening here:
You are slicing your object.
Your f() function is not an override because it is not virtual, and really you should not be doing this.
You would overcome the slicing by making the function g take its first parameter by reference. If A was given a protected copy-constructor that would also prevent it, although then you would not be able to copy genuine instances of A.
In this case your function g will always call A::f() even with reference to A because there is no polymorphism. To invoke that you will need to declare A::f() as virtual.
"Non-scientific" explanation:
The function g treats a as if it was an instance of A gets a copy of p as an object of type A(see comments below) , and executes the f from within A. b is treated as an instance of B, where the method B.f overrides A.f, so when b is "looked at" as an instance of B and we execute b.f, the method B.f will be executed, because the A.f is not visible
If you'd like to call A.f using b.f you'd have to cast b to A: ((A)b).f().
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.
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.
I have following classes.
class A
{
public:
void fun();
}
class B: public A
{
}
class C: public A
{
}
A * ptr = new C;
Is it ok to do something like below? Will i have some problems if introduce some virtual functions in the baseclass?
((B *)ptr)->fun();
This may look stupid, but i have a function that calls A's function through B and i don't want to change that.
You can't cast an A* pointing to Class C as a B* because Class C doesn't have any relation with Class B. You'll get undefined behavior which will probably be the wrong function called and stack corruption.
If you intended for class C to derive from class B then you could. However, you wouldn't need to. If class C doesn't have fun() defined, it will inherit A's. You didn't declare fun() virtual though so you'll get strange behavior if you even implement C::fun() or B::fun(). You almost certainly want fun() to be declared virtual.
I'm guessing here but I suspect the behavior of this might depend on the compiler you use and how it decides to organize the vf pointer table.
I'm also going to note that I think what you are doing is a bad idea and could lead to all kinds of nightmarish problems (use of things like static_cast and dynamic_cast are generally a good idea). The other thing is because fun() is defined in the base class (and it is not virtual) ptr->fun() will always call A::fun() without having to cast it to B*.
You don't have to do the casting (B*) ptr->fun(); since the fun() is already in the base class. both objects of class B or C will invoke the same fun() function in your example.
I'm not sure what happens when u override the fun() function in class B...
But trying to invoke function from another class (not the base class) is bad OO, in my opinion.
You can cast from A * to B *, and it should work if the original pointer was B *.
A* p = new B;
B* q = static_cast<B*>(p); // Just work (tm)
But in this case it is a C *, and it is not guaranteed to work, you will end with a dangling pointer, if you are lucky you will get an access violation, if not you man end up silently corrupting your memory.
A* p = new C;
B* q = static_cast<B*>(p); // Owned (tm)