C++ function overload for classes - c++

I have 3 classes
class A {
//...
}
class B : public A {
//...
}
And a class C:
#include "A.h"
#include "B.h"
class C
{
void method(A anObjOfA);
void method(B anObjOfB);
}
Now if I do
B* ptr = new B();
A* ptrToB = ptr;
c.method(*ptrToB);
It calls the method for Objects of type A, not the inherited actual type B.. How can I make sure the right function for the object deepest in the inheritence-tree is called, without actually knowing it's type at compile-time?
PS: I'm sure this is a noob question, for the life of me I can't find any results on this here, as everyone is busy understanding the "virtual" keyword, which is perfectly clear to me but is not the issue here.

Because resolving a function overload is done at compile-time. When you call the function it only sees the A part of the pointer, even though it could point to a B.
Perhaps what you want is the following:
class A
{
public:
virtual void DoWorkInC()
{
cout << "A's work";
}
virtual ~A() {}
};
class B : public A
{
public:
virtual void DoWorkInC()
{
cout << "B's work";
}
};
class C
{
void method(A& a)
{
a.DoWorkInC();
}
}

Let your class A, B have virtual function implemented in their respectivbe classes:
class A {
//...
public:
virtual void doTask();
};
class B : public A {
//...
public:
void doTask();
};
Ket A::doTask() and B::doTask() do respective tasks in object specific way, i.e. A::doTask() to do tasks with visibility of the object set as an A object, and B::doTask() to do tasks with visibility of the object set as an B object.
Now, let the call be like this:
B* ptr = new B();
A* ptrToB = ptr;
c.method(ptrToB); // pointer is passed
Within C::method(A *ptr), it may be something like:
void C::method(A * ptr) {
ptr->doTask(); this would actuall call A::doTask() or B::doTask() as dynamically binded
}

thanks to #texasbruce I found the answer, RTTI
The code will look like this:
A* someAOrBPtr = ...
...
B* testBPtr = dynamic_cast<B*>(someAOrBPtr);
if( testBPtr ){
// our suspicions are confirmed -- it really was a B
C->method(testBPtr);
}else{
// our suspicions were incorrect -- it is definitely not a B.
// The someAOrBPtr points to an instance of some other child class of the base A.
C->method(someAOrBPtr);
};
EDIT: In fact, I'll probably do the dynamic cast inside the C->method so there is only one
C::method(A* ptrOfBase)
and then do the appropriate thing (taking in or out the respective container-member-variable of C) inside the one 'method' of C.

Compiler is not smart enough to guess which method you wanna call. In the same situation of yours, you might actually want to call the the first version since you are using a A*. This leaves the programmer to work on: be specific. If you don't want to use ptr (which call the second version as you wished), you need to specifically cast it:
c.method(*((B*)ptrToB));
or better using dynamic cast:
c.method(*dynamic_cast<B*>(ptrToB));
This could be unsafe because you are "downcasting" in which case dynamic cast may throw exception and C style cast won't but will cause memory leak. You have to be very careful.

Related

Member function in another thread loses its classes pointers

I'm currently working on a SDL_Project that includes Timers.
A SDL_Timer can have a callback function, and since my timer is located in a class this callbackfunction is a static member function to which I pass "this" via void*-argument.
But the class has also another member variable, which is a pointer. But as soon as I call the callbackfunction, these pointers aren't valid anymore. Which kinda makes sense, I suppose, since the static function is called in another thread.
Is there a way to get around this problem? I'm not very familiar with Multithreading, so I have no idea what to look for.
This is a basic representation of what I'm doing, though this examples works just fine, since it's all in one thread, if my theory is right.
//A is just an interface so that B can hold a pointer to it
class A
{
public:
virtual int get() = 0;
};
class C
{
public:
C(){};
C(A* parent_arg)
{
parent = parent_arg;
}
void (*fptr)(C* sender) = nullptr;
static void callback(void* param)
{
//In my actual program, me has lost its parent pointer
C* me = (C*)param;
me->fptr(me);
};
//In my actual code, this function is from a SDL_Timer and
//runs in another thread
void Go()
{
callback(this);
}
A* parent = nullptr;
};
class B : A
{
public:
B()
{
c.parent = this;
};
virtual int get() { return myint; };
C c;
private:
int myint = 5;
};
void myfun (C* sender)
{
std::cout << sender->parent->get() << "\n";
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
b.c.fptr = myfun;
b.c.Go();
int test;
std::cin >> test;
return 0;
}
Edit:
Here is a little more information about what I do with C and B after they're created and how they are implemented in the actual program.
All of the classes involved are copy constructable. And the member variable c in B is in a boost::stable_vector. Since for other tasks this all works fine, I assume that my copy constructors and assignment operators are ok.
If I check the values of me in the callback, it turns out that me itself has still all its values in place, except the pointers.
Edit2:
I found the problem. I didn't update the parent pointer when I copied B object. Thank you all for your help.
You provided too little information to answer you with certainty. Most likely the object b gets destroyed (probably from the thread it was created in) before callback is called from another thread.
Add a destructor with some logging to class B. Add some logging in the beginning of C::callback() as well, this will give you a hint what's happening. And also, add a virtual destructor to A, it's crucial in case you have something like A* a = new B(); delete a;.
If you can't detect issues through manual code review use valgrind memcheck/helgrind to help you out with detecting any potential memory corruption issues.

Does a static_cast of a derived object to base always select most derived object?

In the artificial example below, if I static_cast to the base class, when I call the setSnapshot() function it still calls the actual object setSnapshot(). This is what I want to happen. My question is can I always rely on this to work?
In code I am working on, we have this class hierarchy and in the b class there are macros used which static cast to the b type. This is to downcast from a base type so that specialised function in b can be called.
#include <iostream>
class a {
};
class b: public a {
public:
virtual void setSnapshot() { std::cout << "setting b snapshot\n"; }
};
class c : public b {
public:
virtual void setSnapshot() { std::cout << "setting c snapshot\n"; }
};
int main() {
a* o = new c;
//specifically casting to b
static_cast<b*>(o)->setSnapshot(); //prints setting c snapshot - what I want to happen
delete o;
return 0;
}
The title suggests that you're misunderstanding what the case does. new c creates an object of type c, and it will remain a c until it's destructed.
If you were to cast it to an a, you'd create a copy. But yu're only casting pointers. That doesn't affect the original object. That's still a c, and that's why you end up calling c::setSnapshot().
As long as a function is virtual in the statically known type a call of it will go to the override that is most derived.
For single inheritance this can be understood as a search for an implementation up the base class chain, starting in the most derived class.
In practice, for C++, the dynamic search is not done, and the effect of the search is instead implemented as a simple table lookup.

Pointer to virtual function

So I'm in a bit of a dilemma right now. I want to make a function pointer, but I want to make it to a virtual function. Not necessarily the virtual function itself, but the derived one. I tried just making the pointer, but the function needs to be static. When I try to make a static virtual function, the compiler yells at me. I also don't want to make the function pointer class specific so conceivably other classes could use the pointer. Here is what I mean in pseudocode:
class C
{
public:
virtual void something();
};
class B : public C
{
public:
void something();
};
class D
{
public:
void something();
};
int main()
{
void(*pointer)();
B b;
D d;
pointer = b.something.
pointer();
pointer = d.something;
pointer()
}
Something is not a static method but I want the pointer to be able to point to it. Also the pointer can point to other class methods that are also not static. Is there anything I can do with this?
EDIT
I finally was able to figure out how to do this. I had to use std::function. This should also work for just regular member functions, not necessarily virtual one. Here is what it would look like:
class A
{
public:
virtual void something(int i);
};
class B
{
virtual void somethingElse(int i);
}
//This isn't needed, it just saves typing if you have multiple pointers
typedef std::function<void(int)> functionType
functionType* pointer;
int main()
{
B b;
A a;
pointer = std::bind(&A::something,&a,std::placeholders::_1);
pointer(1)
pointer = std::bind(&B::somethingElse,&b,std::placeholders::_1);
pointer(4)
}
Theres quite a bit on the internet on std::bind, so if you're curious you can read about it.
I found this particularly helpful, as it has a very similar solution to what I have.
std::function to member function
Thanks to all who have helped.
You won't be able to assign a pointer-to-member function to a normal function pointer: function pointers don't take any additional arguments while member function take an implicit this pointer as argument. You might want to use a std::function<...>, though:
std::function<void()> pointer;
B b;
pointer = std::bind(&C::something, &b);
pointer();
D d;
pointer = std::bind(&c::something, &d);
pointer();
You could avoid using std::function<...> if you pass a pointer to the object and a suitable member function pointer around and there is common base class (while the code above works with the missing inheritance, the code below requires that C is a base of D):
void (C::*member)() = &C::something;
C* c = &b;
(c->*member)(); // calls b.something() using B::something()
c = &d;
(c->*member)(); // calls d.something() using D::something()
C++ doesn't have a notation using &object.member to get the address of a readily bound member function. ... and, even if it did, its type wouldn't be void(*)() either.
void(B::*bPointer)();
void(D::*dPointer)();
B b;
D d;
bPointer = &B::something;
(b.*bpointer)();
dPointer = &D::something;
(d.*dPointer)();
You can also use std::mem_fn and std::bind.
There are so many things wrong here it's hard to know where to begin.
This:
void(*pointer)();
does not declare a pointer-to-member-function. It declares a pointer-to-free-function (eg, non-member function). These two types of pointers are completely unrelated, and you cannot convert between the two. You can not assign the address of a member function to a pointer-to-free-function, or vice versa.
You need to declare a pointer-to-member with special syntax. The old (C++03) syntax would be:
void (C::*memFn)()
However, since the type of the pointer includes information about the class that the function is a member of, now you can't assign the address D::something() to memFn -- C and D are completely unrelated as well.
You mentioned that you wanted to create a "static virtual method." There's no such thing. In fact the two concepts "static" and "virtual" are almost completely orthogonal to each other. The idea simply makes no sense. It's like saying you want to plant an apple hammer.
Why are you trying to use the D object as if it were a B object? D and B are completely unrelated. It seems to me like what you really should be trying to do is have an abstract base class, A, and 2 concrete implementations of that ABC, B and C. Then a pointer to an A could point to either a B or a C, and you could call virtual methods of the same name and get different behavior.
Finally, for the last couple of days you have posted questions that indicate that you are struggling to learn the language by banging out some code and trying to fix whatever compiler errors result. (I might be thinking of someone else, if so I'm sorry) That's not going to work. Have you taken my advice and gotten a good C++ text yet?
S.th. like
pointer = &D::dosomething;
May be??
Note:
You'll need to have an actual instance of D to call non-static class members.
#include <iostream>
class A
{
private:
int i;
protected:
void (A::*ptr)();
public:
A() : i(0), ptr(&A::methodOne) {}
virtual ~A(){}
void move_ptr()
{
switch(++i)
{
case 0: {ptr = &A::methodOne;} break;
case 1: {ptr = &A::methodTwo;} break;
case 2: {ptr = &A::methodThree;} break;
case 3: {ptr = &A::nonVirtual;} break;
default: {ptr = &A::methodOne; i = 0;} break;
}
}
void call() {(this->*A::ptr)();}
virtual void methodOne() {std::cout<<"A::methodOne\n";}
virtual void methodTwo() {std::cout<<"A::methodTwo\n";}
virtual void methodThree() {std::cout<<"A::methodThree\n";}
void nonVirtual() {std::cout<<"A::nonVirtual\n";}
};
class B : public A
{
public:
B() : A() {}
virtual ~B(){}
virtual void methodOne() {std::cout<<"B::methodOne\n";}
virtual void methodTwo() {std::cout<<"B::methodTwo\n";}
virtual void methodThree() {std::cout<<"B::methodThree\n";}
void nonVirtual() {std::cout<<"B::nonVirtual\n";}
};
int main()
{
A a;
a.call();
a.move_ptr();
a.call();
a.move_ptr();
a.call();
a.move_ptr();
a.call();
B b;
b.call();
b.move_ptr();
b.call();
b.move_ptr();
b.call();
b.move_ptr();
b.call();
}
Prints:
A::methodOne
A::methodTwo
A::methodThree
A::nonVirtual
B::methodOne
B::methodTwo
B::methodThree
A::nonVirtual
I'll leave it to you to figure out why the last line is A::nonVirtual instead of B::nonVirtual. Once you figure that out, you'll already know how to fix it.

Can you explain how the methods of the class are called?

conv.h
class Base
{
public:
void foo();
};
class Derived: public Base
{
public:
void bar();
};
class A {};
class B
{
public:
void koko();
};
conv.cpp
void Base::foo()
{
cout<<"stamm";
}
void Derived::bar()
{
cout<<"bar shoudn't work"<<endl;
}
void B::koko()
{
cout<<"koko shoudn't work"<<endl;
}
main.cpp
#include "conv.h"
#include <iostream>
int main()
{
Base * a = new Base;
Derived * b = static_cast<Derived*>(a);
b->bar();
Derived * c = reinterpret_cast<Derived*>(a);
c->bar();
A* s1 = new A;
B* s2 = reinterpret_cast<B*>(s1);
s2->koko();
}
output:
bar shoudn't work
bar shoudn't work
koko shoudn't work
How come the method bar is succeeded to be called in run time despite that I have created a Base class not derived?? it works even with two types of conversions (static and reinterpret cast).
same question as above but with unrelated classes (A & B) ??
Undefined behaviour can do anything, including appear to work.
It's working (read: "compiling and not crashing") 'cause you never use the this pointer in your nominally "member" functions. If you tried to print out a member variable, for example, you'd get the garbage output or crashes you expect - but these functions as they are now don't depend on anything in the classes they're supposedly part of. this could even be NULL for all they care.
The compiler knows a Derived can use member functions foo() and bar() and knows where to find them. After you did your "tricks", you had pointers to Derived.
The fact that they were pointers of type Derived -- regardless of what data was associated with those pointers -- allowed them to call the functions foo() and kook() associated with Derived.
As has been mentioned, if you had actually used the data at the pointers (i.e. read or wrote data members relative to this belonging to the Derived class (which you don't have in this case), you would have been access memory that didn't belong to your objects.

Trouble understanding C++ `virtual`

I'm having trouble understanding what the purpose of the virtual keyword in C++. I know C and Java very well but I'm new to C++
From wikipedia
In object-oriented programming, a
virtual function or virtual method is
a function or method whose behavior
can be overridden within an inheriting
class by a function with the same
signature.
However I can override a method as seen below without using the virtual keyword
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : A {
public:
int a();
};
int B::a() {
return 2;
}
int main() {
B b;
cout << b.a() << endl;
return 0;
}
//output: 2
As you can see below, the function A::a is successfully overridden with B::a without requiring virtual
Compounding my confusion is this statement about virtual destructors, also from wikipedia
as illustrated in the following example,
it is important for a C++ base class
to have a virtual destructor to ensure
that the destructor from the most
derived class will always be called.
So virtual also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of virtual as "make the function overridable"
Make the following changes and you will see why:
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : public A { // Notice public added here
public:
int a();
};
int B::a() {
return 2;
}
int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 1 instead of 2
delete b; // Added delete to free b
return 0;
}
Now, to make it work like you intended:
#include <iostream>
using namespace std;
class A {
public:
virtual int a(); // Notice virtual added here
};
int A::a() {
return 1;
}
class B : public A { // Notice public added here
public:
virtual int a(); // Notice virtual added here, but not necessary in C++
};
int B::a() {
return 2;
}
int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 2 as intended
delete b; // Added delete to free b
return 0;
}
The note that you've included about virtual destructors is exactly right. In your sample there is nothing that needs to be cleaned-up, but say that both A and B had destructors. If they aren't marked virtual, which one is going to get called with the base class pointer? Hint: It will work exactly the same as the a() method did when it was not marked virtual.
You could think of it as follows.
All functions in Java are virtual. If you have a class with a function, and you override that function in a derived class, it will be called, no matter the declared type of the variable you use to call it.
In C++, on the other hand, it won't necessarily be called.
If you have a base class Base and a derived class Derived, and they both have a non-virtual function in them named 'foo', then
Base * base;
Derived *derived;
base->foo(); // calls Base::foo
derived->foo(); // calls Derived::foo
If foo is virtual, then both call Derived::foo.
virtual means that the actual method is determined runtime based on what class was instantiated not what type you used to declare your variable.
In your case this is a static override it will go for the method defined for class B no matter what was the actual type of the object created
So virtual also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of virtual as "make the function overridable"
Your original and your new understanding are both wrong.
Methods (you call them functions) are always overridable. No matter if virtual, pure, nonvirtual or something.
Parent destructors are always called. As are the constructors.
"Virtual" does only make a difference if you call a method trough a pointer of type pointer-to-baseclass. Since in your example you don't use pointers at all, virtual doesn't make a difference at all.
If you use a variable a of type pointer-to-A, that is A* a;, you can not only assign other variables of type pointer-to-A to it, but also variables of type pointer-to-B, because B is derived from A.
A* a;
B* b;
b = new B(); // create a object of type B.
a = b; // this is valid code. a has still the type pointer-to-A,
// but the value it holds is b, a pointer to a B object.
a.a(); // now here is the difference. If a() is non-virtual, A::a()
// will be called, because a is of type pointer-to-A.
// Whether the object it points to is of type A, B or
// something entirely different doesn't matter, what gets called
// is determined during compile time from the type of a.
a.a(); // now if a() is virtual, B::a() will be called, the compiler
// looks during runtime at the value of a, sees that it points
// to a B object and uses B::a(). What gets called is determined
// from the type of the __value__ of a.
As you can see below, the function A::a is successfully overridden with B::a without requiring virtual
It may, or it may not work. In your example it works, but it's because you create and use an B object directly, and not through pointer to A. See C++ FAQ Lite, 20.3.
So virtual also tells the compiler to call up the parent's destructors?
A virtual destructor is needed if you delete a pointer of base class pointing to an object of derived class, and expect both base and derived destructors to run. See C++ FAQ Lite, 20.7.
You need the virtual if you use a base class pointer as consultutah (and others while I'm typing ;) ) says it.
The lack of virtuals allows to save a check to know wich method it need to call (the one of the base class or of some derived). However, at this point don't worry about performances, just on correct behaviour.
The virtual destructor is particulary important because derived classes might declare other variables on the heap (i.e. using the keyword 'new') and you need to be able to delete it.
However, you might notice, that in C++, you tend to use less deriving than in java for example (you often use templates for a similar use), and maybe you don't even need to bother about that. Also, if you never declare your objects on the heap ("A a;" instead of "A * a = new A();") then you don't need to worry about it either. Of course, this will heavily depend on what/how you develop and if you plan that someone else will derive your class or not.
Try ((A*)&b).a() and see what gets called then.
The virtual keyword lets you treat an object in an abstract way (I.E. through a base class pointer) and yet still call descendant code...
Put another way, the virtual keyword "lets old code call new code". You may have written code to operate on A's, but through virtual functions, that code can call B's newer a().
Say you instantiated B but held it as an instance of an A:
A *a = new B();
and called function a() whose implementation of a() will be called?
If a() isn't virtual A's will be called. If a() was virtual the instantiated sub class version of a() would be called regardless of how you're holding it.
If B's constructor allocated tons of memory for arrays or opened files, calling
delete a;
would ensure B's destructor was called regardless as to how it was being held, be it by a base class or interface or whatever.
Good question by the way.
I always think about it like chess pieces (my first experiment with OO).
A chessboard holds pointers to all the pieces. Empty squares are NULL pointers. But all it knows is that each pointer points a a chess piece. The board does not need to know more information. But when a piece is moved the board does not know it is a valid move as each pice has different characteristica about how it moves. So the board needs to check with the piece if the move is valid.
Piece* board[8][8];
CheckMove(Point const& from,Point const& too)
{
Piece* piece = board[from.x][from.y];
if (piece != NULL)
{
if (!piece->checkValidMove(from,too))
{ throw std::exception("Bad Move");
}
// Other checks.
}
}
class Piece
{
virtual bool checkValidMove(Point const& from,Point const& too) = 0;
};
class Queen: public Piece
{
virtual bool checkValidMove(Point const& from,Point const& too)
{
if (CheckHorizontalMove(from,too) || CheckVerticalMoce(from,too) || CheckDiagonalMove(from,too))
{
.....
}
}
}