Polymorphism misunderstanding / redefined virtual function not working - c++

I think I should start by simplifying my class structure so I can better explain my problem, which I suspect might just be a misunderstanding of the use of virtual.
I have:
class Controller{
..
virtual void InitialiseController(){ //std::cout confirms this is running }
..
}
class AIController : public Controller{
..
virtual void InitialiseController(){ //some logic here }
..
}
class ComController : public AIController{
..
virtual void InitialiseController(){ //actually the same logic as parent }
..
}
My object, Snake, has a pointer to a Controller (Controller* _controller). When I call the snake.initialise(..) method I pass it a new ComController object which then sets snakes _controller equal to the new ComController. I know that that process works successfully.
But when I then call _controller.InitialiseController(); my debugger shows the program steps into the base class Controller's blank implementation of InitialiseContoller.
I know I've probably oversimplified and you might not be able to help, but I think perhaps it's something I'm not understanding about the whole concept, a logic error, rather than a typed error and would like to check.
Additional code:
_player2->Initialise(_gameProperties, &_fruitManager, new ComController(_player2), _player1);
stepping in ..
void Snake::Initialise(
GamePropertiesManager* gpm, FruitManager* fm, Controller* control, Snake* opposingSnake)
{
_game = gpm;
_fruitManager = fm;
_controller = control;
_opposition = opposingSnake;
if(_controller){
///Bunch of stuff in here runs just fine
// This primarily serves to ensure that a ComControllers timer is started, but other controllers might wish to override initialise later
_controller->IntialiseController();
}
}

I don't really see anything wrong with what you're doing (at least as far as understanding and using virtual methods).
Here's a complete example. Please compare it with your code.
#include <stdio.h>
class Controller{
public:
virtual void InitialiseController(){
printf ("base class controller...\n");
}
};
class AIController : public Controller{
public:
virtual void InitialiseController(){
printf ("AIController subclass controller...\n");
}
};
class ComController : public AIController{
public:
virtual void InitialiseController(){
printf ("ComController subclass controller...\n");
}
};
int main (int argc, char *argv[])
{
Controller *myController = new ComController ();
myController->InitialiseController ();
return 0;
}
Compile:
g++ -Wall -pedantic -o tmp tmp.cpp
Execute:
ComController subclass controller...

I think you're calling the virtual method on the object directly. Polymorphism kicks in only if you call via a pointer or reference.
Edit: You write both _controller.InitialiseController(); and _controller->InitialiseController(); (was that there before?), so I'm not entirely sure what you're doing.

Related

Setting a pointer to another pointer breaks reference somehow

Based on my understanding of pointers here, currentDancer and pushups should be the same reference. And yet if I set currentDancer I can't use it.
Dancer *currentDancer;
DancerPushups pushups; // DancerPushups inherits from public Dancer
void setup() {
pushUps.init(FL1, FL2, FR1, FR2, BR1, BR2, BL1, BL2);
currentDancer = &pushups; // try to set pushups as the current dancer
}
void loop() {
pushups.onBeatStart(duration); // works great! :D
currentDancer->onBeatStart(duration); // does nothing D:
}
What part of pointer handling am I failing here? How can I get Dancer *currentDancer to point to an arbitrary instance that I already have created?
UPDATE:
Is this an inheritance issue?
void Dancer::onBeatStart(float duration) {
// no-op
}
// DancerPushups : public Dancer
void DancerPushups::onBeatStart(float duration) {
all(the, cool, stuff, that, isnt, happening);
}
Because I'm casting the DancerPushups to a Dancer* type, am I not running my subclasses method?
Sounds like onBeatStart is not a virtual member function. When you call currentDancer->onBeatStart(), you are calling the base class implementation, which, as you have shown, does nothing.

undefined reference in pure virtual function C++

I am having some difficulties with a c++ program that I need to run. The problem itself is not mine and I have to make it compile. The algorithm is pretty huge so for my current error message I will demonstrate a much more simplified version of a code that I produced that gives me the exact same error. Here is the code:
class_1.h (class_1.cpp is empty)
class class_1 {
public:
class_1();
virtual ~class_1();
virtual void function() =0;
};
class_2.h (class_2.cpp is empty)
include"class_1.h";
class class_2 : public class_1{
public:
class_2();
virtual ~class_2();
virtual void function();
};
class_2a.h (class_2a.cpp is empty)
include"class_2.h";
class class_2a : public flos2{
public:
class_2a();
virtual ~class_2a();
};
class_3.h
include "class_2a.h"
include "class_1.h" //I tried unsuccesfully without including class_1.h as well
class class_3 {
public:
class_3();
virtual ~class_3();
virtual void function();
private:
class_2a my_class_2a;
};
class_3.cpp
#include "class_3.h"
class_3::class_3()
:my_class_2a()
{
}
class_3::~class_3()
{
this->function();
}
void flos3::function()
{
my_class_2a.function();
/***Main Body of function***/
}
};
The error I am getting is linker error:
undefined reference to `class_2::function()'
I know that in general the whole algorithm seems to be stupid, but more or less this is the what I was given and I am not allowed to change the structure itself, just to make it working. As you can see in class_1 function is defined as a pure virtual function, and then is called through the other classes. I really don't know how to make this thing work, so any help would be really appreciated...
You need to add:
class_1.cpp:
class_1::~class_1() = default;
class_2.cpp:
class_2::~class_2() = default;
void class_2::function() {
// add code here (or not)
}
... and so on.
You are getting linker error because your function class_2::function() does not have implementation. You need to add it, preferably in class_2.cpp file.
void class_2::function()
{
// Implementation goes here
}
Similar problem is with all virtual destructors. They need implementations as well.

C++ object oriented return value of virtual function in base class

I am making a class which inherits off another and must return the value of a function in the base class... It is confusing so I will let the code speak for itself...
class ParentClass {
public:
virtual bool getMyVal();
};
bool ParentClass::getMyVal() {
return true; // in my program there is a bit more to it
}
class ChildClass : public ParentClass {
public:
bool getMyVal();
};
bool ChildClass::getMyVal() {
CalculateMassOfSun();
return parent::getMyVal(); // Please make sure you read below...
}
So this is just an example of what I want to do, not the actual code. As you can see, in ChildClass::getMyVal(), is basically needs to do some pre-computation then run the same function in the parent class and return its value. I know that it is a virtual function in the parent, and that I have not gone about invoking the function in the parent the right way - it is how it is done in PHP and the only way I can think of that makes sense to me and hopefully others at the moment.
So how would I go about doing this? At the moment, I have found something along the lines of:
bool ChildClass::getMyVal() : /*ParentClass::*/getMyVal() { ... }
however it does not return the value here.
Thanks in advance for your responses.
To invoke the base definition of getMyVal just prefix the call with the base type name
return ParentClass::getMyVal();
If you want to call ParentClass version of getMyVal() then do this:
bool ChildClass::getMyVal() {
CalculateMassOfSun();
return ParentClass::getMyVal(); // this will call parent version
}

Optional Member Objects

Okay, so you have a load of methods sprinkled around your system's main class. So you do the right thing and refactor by creating a new class and perform move method(s) into a new class. The new class has a single responsibility and all is right with the world again:
class Feature
{
public:
Feature(){};
void doSomething();
void doSomething1();
void doSomething2();
};
So now your original class has a member variable of type object:
Feature _feature;
Which you will call in the main class. Now if you do this many times, you will have many member-objects in your main class.
Now these features may or not be required based on configuration so in a way it's costly having all these objects that may or not be needed.
Can anyone suggest a way of improving this?
EDIT: Based on suggestion to use The Null Object Design Pattern I've come up with this:
An Abstract Class Defining the Interface of the Feature:
class IFeature
{
public:
virtual void doSomething()=0;
virtual void doSomething1()=0;
virtual void doSomething2()=0;
virtual ~IFeature(){}
};
I then define two classes which implement the interface, one real implementation and one Null Object:
class RealFeature:public IFeature
{
public:
RealFeature(){};
void doSomething(){std::cout<<"RealFeature doSomething()"<<std::endl;}
void doSomething1(){std::cout<<"RealFeature doSomething()"<<std::endl;}
void doSomething2(){std::cout<<"RealFeature doSomething()"<<std::endl;}
};
class NullFeature:public IFeature
{
public:
NullFeature(){};
void doSomething(){std::cout<<"NULL doSomething()"<<std::endl;};
void doSomething1(){std::cout<<"NULL doSomething1()"<<std::endl;};
void doSomething2(){std::cout<<"NULL doSomething2()"<<std::endl;};
};
I then define a Proxy class which will delegate to either the real object or the null object depending on configuration:
class Feature:public IFeature
{
public:
Feature();
~Feature();
void doSomething();
void doSomething1();
void doSomething2();
private:
std::auto_ptr<IFeature> _feature;
};
Implementation:
Feature::Feature()
{
std::cout<<"Feature() CTOR"<<std::endl;
if(configuration::isEnabled() )
{
_feature = auto_ptr<IFeature>( new RealFeature() );
}
else
{
_feature = auto_ptr<IFeature>( new NullFeature() );
}
}
void Feature::doSomething()
{
_feature->doSomething();
}
//And so one for each of the implementation methods
I then use the proxy class in my main class (or wherever it's required):
Feature _feature;
_feature.doSomething();
If a feature is missing and the correct thing to do is ignore that fact and do nothing, you can get rid of your checks by using the Null Object pattern:
class MainThing {
IFeature _feature;
void DoStuff() {
_feature.Method1();
_feature.Method2();
}
interface IFeature {
void Method1();
void Method2();
}
class SomeFeature { /* ... */ }
class NullFeature {
void Method1() { /* do nothing */ }
void Method2() { /* do nothing */ }
}
Now, in MainThing, if the optional feature isn't there, you give it a reference to a NullFeature instead of an actual null reference. That way, MainThing can always safely assume that _feature isn't null.
An auto_ptr by itself won't buy you much. But having a pointer to an object that you lazily load only when and if you need it might. Something like:
class Foo {
private:
Feature* _feature;
public:
Foo() : _feature(NULL) {}
Feature* getFeature() {
if (! _feature) {
_feature = new Feature();
}
return _feature;
}
};
Now you can wrap that Feature* in a smart pointer if you want help with the memory management. But the key isn't in the memory management, it's the lazy creation. The advantage to this instead of selectively configuring what you want to go create during startup is that you don't have to configure – you simply pay as you go. Sometimes that's all you need.
Note that a downside to this particular implementation is that the creation now takes place the first time the client invokes what they think is just a getter. If creation of the object is time-consuming, this could be a bit of a shock to, or even a problem for, to your client. It also makes the getter non-const, which could also be a problem. Finally, it assumes you have everything you need to create the object on demand, which could be a problem for objects that are tricky to construct.
There is one moment in your problem description, that actually would lead to failure. You shouldn't "just return" if your feature is unavailable, you should check the availability of your feature before calling it!
Try designing that main class using different approach. Think of having some abstract descriptor of your class called FeatureMap or something like that, which actually stores available features for current class.
When you implement your FeatureMap everything goes plain and simple. Just ensure (before calling), that your class has this feature and only then call it. If you face a situation when an unsupported feature is being called, throw an exception.
Also to mention, this feature-lookup routine should be fast (I guess so) and won't impact your performance.
I'm not sure if I'm answering directly to your question (because I don't have any ideas about your problem domain and, well, better solutions are always domain-specific), but hope this will make you think in the right way.
Regarding your edit on the Null Object Pattern: If you already have a public interface / private implementation for a feature, it makes no sense to also create a null implementation, as the public interface can be your null implementation with no problems whatsoever).
Concretely, you can have:
class FeatureImpl
{
public:
void doSomething() { /*real work here*/ }
};
class Feature
{
class FeatureImpl * _impl;
public:
Feature() : _impl(0) {}
void doSomething()
{
if(_impl)
_impl->doSomething();
// else case ... here's your null object implementation :)
}
// code to (optionally) initialize the implementation left out due to laziness
};
This code only benefits from a NULL implementation if it is performance-critical (and even then, the cost of an if(_impl) is in most cases negligible).

calling a function from a set of overloads depending on the dynamic type of an object

I feel like the answer to this question is really simple, but I really am having trouble finding it. So here goes:
Suppose you have the following classes:
class Base;
class Child : public Base;
class Displayer
{
public:
Displayer(Base* element);
Displayer(Child* element);
}
Additionally, I have a Base* object which might point to either an instance of the class Base or an instance of the class Child.
Now I want to create a Displayer based on the element pointed to by object, however, I want to pick the right version of the constructor. As I currently have it, this would accomplish just that (I am being a bit fuzzy with my C++ here, but I think this the clearest way)
object->createDisplayer();
virtual void Base::createDisplayer()
{
new Displayer(this);
}
virtual void Child::createDisplayer()
{
new Displayer(this);
}
This works, however, there is a problem with this:
Base and Child are part of the application system, while Displayer is part of the GUI system. I want to build the GUI system independently of the Application system, so that it is easy to replace the GUI. This means that Base and Child should not know about Displayer. However, I do not know how I can achieve this without letting the Application classes know about the GUI.
Am I missing something very obvious or am I trying something that is not possible?
Edit: I missed a part of the problem in my original question. This is all happening quite deep in the GUI code, providing functionality that is unique to this one GUI. This means that I want the Base and Child classes not to know about the call at all - not just hide from them to what the call is
It seems a classic scenario for double dispatch. The only way to avoid the double dispatch is switching over types (if( typeid(*object) == typeid(base) ) ...) which you should avoid.
What you can do is to make the callback mechanism generic, so that the application doesn't have to know of the GUI:
class app_callback {
public:
// sprinkle const where appropriate...
virtual void call(base&) = 0;
virtual void call(derived&) = 0;
};
class Base {
public:
virtual void call_me_back(app_callback& cb) {cb.call(*this);}
};
class Child : public Base {
public:
virtual void call_me_back(app_callback& cb) {cb.call(*this);}
};
You could then use this machinery like this:
class display_callback : public app_callback {
public:
// sprinkle const where appropriate...
virtual void call(base& obj) { displayer = new Displayer(obj); }
virtual void call(derived& obj) { displayer = new Displayer(obj); }
Displayer* displayer;
};
Displayer* create_displayer(Base& obj)
{
display_callback dcb;
obj.call_me_back(dcb);
return dcb.displayer;
}
You will have to have one app_callback::call() function for each class in the hierarchy and you will have to add one to each callback every time you add a class to the hierarchy.
Since in your case calling with just a base& is possible, too, the compiler won't throw an error when you forget to overload one of these functions in a callback class. It will simply call the one taking a base&. That's bad.
If you want, you could move the identical code of call_me_back() for each class into a privately inherited class template using the CRTP. But if you just have half a dozen classes it doesn't really add all that much clarity and it requires readers to understand the CRTP.
Have the application set a factory interface on the system code. Here's a hacked up way to do this. Obviously, apply this changes to your own preferences and coding standards. In some places, I'm inlining the functions in the class declaration - only for brevity.
// PLATFORM CODE
// platformcode.h - BEGIN
class IDisplayer;
class IDisplayFactory
{
virtual IDisplayer* CreateDisplayer(Base* pBase) = 0;
virtual IDisplayer* CreateDisplayer(Child* pBase) = 0;
};
namespace SystemDisplayerFactory
{
static IDisplayFactory* s_pFactory;
SetFactory(IDisplayFactory* pFactory)
{
s_pFactory = pFactory;
}
IDisplayFactory* GetFactory()
{
return s_pFactory;
}
};
// platformcode.h - end
// Base.cpp and Child.cpp implement the "CreateDisplayer" methods as follows
void Base::CreateDisplayer()
{
IDisplayer* pDisplayer = SystemDisplayerFactory::GetFactory()->CreateDisplayer(this);
}
void Child::CreateDisplayer()
{
IDisplayer* pDisplayer = SystemDisplayerFactory::GetFactory()->CreateDisplayer(this);
}
// In your application code, do this:
#include "platformcode.h"
class CDiplayerFactory : public IDisplayerFactory
{
IDisplayer* CreateDisplayer(Base* pBase)
{
return new Displayer(pBase);
}
IDisplayer* CreateDisplayer(Child* pChild)
{
return new Displayer(pChild);
}
}
Then somewhere early in app initialization (main or WinMain), say the following:
CDisplayerFactory* pFactory = new CDisplayerFactory();
SystemDisplayFactory::SetFactory(pFactory);
This will keep your platform code from having to know the messy details of what a "displayer" is, and you can implement mock versions of IDisplayer later to test Base and Child independently of the rendering system.
Also, IDisplayer (methods not shown) becomes an interface declaration exposed by the platform code. Your implementation of "Displayer" is a class (in your app code) that inherits from IDisplayer.