Calling a non-virtual function in derived class using a base class pointer - c++

As noted in this answer:
high reliance on dynamic_cast is often an indication your design has gone wrong.
What I'd like to know is how can I call a custom function in a derived class, for which there is no same-name function in the base class, but do so using a base class pointer and perhaps without dynamic_cast if in fact there is a better way.
If this function was a virtual function defined in both, that's easy. But this is a unique function only in the derived class.
Perhaps dynamic_cast is the best way afterall?

In order to call a function of Derived class you have to obtain a pointer to derived class. As an option (depending on situation) you may want using static_cast instead of dynamic, but as you said:
it is often an indication your design has gone wrong
Also, sometimes I think it's ok to use casts. When I was designing a GUI library for a game it has a base class Widget and lots of subclasses. An actual window layout was made in an editor and later some Loader class was inflating this layout. In order to fill widgets from the layout with actual specific for each widget data (game related) I made a method for quering widget's child from a widget. This function retuned Widget* and then I dynamic_casted it to actual type. I have not found a better design for this.
Later I also found that GUI system on Android works the same way

What I'd like to know is how can I call a custom function in a derived class ... without dynamic_cast if in fact there is a better way
As indicated in the quote, it's a design issue, not an implementation issue. There's no "better way" to call that function; the "better way" is to redesign your types so that subtypes don't need to add functionality to their parents. By doing so, your types satisfy (a common interpretation of) the Liskov Substitution Principle, and are easier to use since users don't need to know about the subtypes at all.
If it's impossible or unreasonably difficult to redesign the types in such a way, then perhaps you do need RTTI. The advice doesn't say "All use of ...", just "High reliance on ...", meaning that RTTI should be a last resort, not a default approach.

This is more like an option then a real answer, so don't stone me to death.
class Derived;
class Base
{
public:
virtual Derived * getDerived()const
{
return NULL;
}
};
class Derived : public Base
{
public:
virtual Derived * getDerived()const
{
return this;
}
};
I guess you get the picture...
P.S. Mike Seymour, thanks :-)

Related

Is it better to cast a base class to derived class or create a virtual function on the base class?

According to this answer, dynamic_cast'ing a base class to derived class is fine, but he says this shows that there is a fundamental problem with the code logic.
I've looked at other answers and using dynamic_cast is fine since you can check the pointer validity later.
Now in my real problem the derived class has a GetStrBasedOnCP function which is not virtual (only the derived class has it) and I have to access it.
What is better, to create a virtual void GetStrBasedOnCP on the base class and make it virtual on the derived OR, to just cast the base class pointer to derived class?
Oh also notice that this is a unsigned int GetStrBasedOnCP so the base class must also return a value...
There are more than two answers to the "what is better" question, and it all depends on what you are modeling:
If the GetStrBasedOnCP function is logically applicable to the base class, using virtual dispatch is the best approach.
If having the GetStrBasedOnCP function in the base class does not make logical sense, you need to use an approach based on the actual type; you could use dynamic_cast, or
You could implement multiple dispatch, e.g. through a visitor or through a map of dynamic types.
The test for logical applicability is the most important one. If GetStrBasedOnCP function is specific to your subclass, adding it to the base class will create maintenance headaches for developers using and maintaining your code.
Multiple dispatch, on the other hand, gives you a flexible approach that lets you access statically typed objects. For example, implementing visitor pattern in your base class lets you make visitors that process the subclass with GetStrBasedOnCP function differently from other subclasses.
Does it make sense for the base class you have to have the virtual function in it?
If it does not then you should not include the function in the base class. Remember that best practices cover the general case. There are times you need to do things you wouldn't normally do to get the code working. The key thing is you need is clear, concise, understandable code
There's a lot of "it depends".
If you can guarantee that the base pointer is the correct child pointer, then you can use dynamic_cast.
If you can't guarantee which child type the base pointer is pointing to, you may want to place the function in the base class.
However, be aware that all children of the base class will get the functionality of whatever you place into the base class. Does it make sense for all the children to have the functionality?
You may want to review your design.

C++ inheritance pattern

I am after your opinion on how best to implement an inheritance pattern in C++. I have two base classes, say
class fooBase{
protected:
barBase* b;
};
class barBase{};
where fooBase has a barBase. I intend to put these classes in a library, so that wherever I have a fooBase it can use its barBase member.
I now intend to create a specialisation of these in a specific program
class fooSpec : public fooBase{};
class barSpec : public barBase{};
Now I want fooSpec::b to point to a barSpec instead of a barBase. I know that I can just initialise b with a new barSpec, but this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
Is there another way that this is often acheived?
Cheers.
Create a method in your specclass to cast the b into the special version.
That way instead of casting it all the time, it looks like a getter.
On the other hand OO is about programming towards interfaces and not objects. So what you are doing here looks like programming towards objects. But the is difficult to see as this example is purely theoretical.
You may consider the template solution:
template <class T>
class fooBase{
protected:
T* b;
};
and then use it as
class fooSpec : public fooBase<barSpec>{};
while ordinarily, the base would be used as fooBase<barBase>.
Is this what you want?
Normally we create a function that has the cast and returns the pointer -- and use that instead of the member directly.
Now I want fooSpec::b to point to a barSpec instead of a barBase.
There's no such thing as fooSpec::b. b belongs to fooBase, and your new class fooSpec is a (specialization of) a fooBase. You can't change the fact that b, a fooBase member, is of type barBase. This is a property of all the instances of fooBase that you can't invalidate in the particular subset of instances concerned by your specialization.
I know that I can just initialise b with a new barSpec, but this would
require me to cast the pointer to a barSpec whenever I wanted to use
specific functions in the specialisation wouldn't it?
Yes and no. Yes, you need to do that cast; but no, you don't need to do it every time. You can encapsulated in a function of fooSpec.
Is there another way that this is often acheived?
Not that I'm aware of.
this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
That depends on whether the method you are trying to invoke is defined in the superclass and whether it is virtual.
You need to cast the pointer before invoking a method if one of the following is true...
The method belongs to the subclass only
The superclass has an implementation of the method and the subclass's implementation does not override the implementation in the superclass. This amounts to a question of whether the function is a virtual function.
Avoid data members in non-leaf classes, use pure virtual getters instead. If you follow this simple rule, your problem solves itself automatically.
This also makes most non-leaf classes automatically abstract, which may seem like an undue burden at first, but you get used to it and eventually realize it's a Good Thing.
Like most rules, this one is not absolute and needs to be broken now and then, but in general it's a good rule to follow. Give it a try.
If it looks too extreme, you may try one of the design patterns that deal with dual hierarchies such as Stairway to Heaven.

Is there any way to avoid declaring virtual methods when storing (children) pointers?

I have run into an annoying problem lately, and I am not satisfied with my own workaround: I have a program that maintains a vector of pointers to a base class, and I am storing there all kind of children object-pointers. Now, each child class has methods of their own, and the main program may or not may call these methods, depending on the type of object (note though that they all heavily use common methods of the base class, so this justify inheritance).
I have found useful to have an "object identifier" to check the class type (and then either call the method or not), which is already not very beautiful, but this is not the main inconvenience. The main inconvenience is that, if I want to actually be able to call a derived class method using the base class pointer (or even just store the pointer in the pointer array), then one need to declare the derived methods as virtual in the base class.
Make sense from the C++ coding point of view.. but this is not practical in my case (from the development point of view), because I am planning to create many different children classes in different files, perhaps made by different people, and I don't want to tweak/maintain the base class each time, to add virtual methods!
How to do this? Essentially, what I am asking (I guess) is how to implement something like Objective-C NSArrays - if you send a message to an object that does not implement the method, well, nothing happens.
regards
Instead of this:
// variant A: declare everything in the base class
void DoStuff_A(Base* b) {
if (b->TypeId() == DERIVED_1)
b->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
b->DoDerived12Stuff();
}
or this:
// variant B: declare nothing in the base class
void DoStuff_B(Base* b) {
if (b->TypeId() == DERIVED_1)
(dynamic_cast<Derived1*>(b))->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
(dynamic_cast<Derived2*>(b))->DoDerived12Stuff();
}
do this:
// variant C: declare the right thing in the base class
b->DoStuff();
Note there's a single virtual function in the base per stuff that has to be done.
If you find yourself in a situation where you are more comfortable with variants A or B then with variant C, stop and rethink your design. You are coupling components too tightly and in the end it will backfire.
I am planning to create many different children classes in different
files, perhaps made by different people, and I don't want to
tweak/maintain the base class each time, to add virtual methods!
You are OK with tweaking DoStuff each time a derived class is added, but tweaking Base is a no-no. May I ask why?
If your design does not fit in either A, B or C pattern, show what you have, for clairvoyance is a rare feat these days.
You can do what you describe in C++, but not using functions. It is, by the way, kind of horrible but I suppose there might be cases in which it's a legitimate approach.
First way of doing this:
Define a function with a signature something like boost::variant parseMessage(std::string, std::vector<boost::variant>); and perhaps a string of convenience functions with common signatures on the base class and include a message lookup table on the base class which takes functors. In each class constructor add its messages to the message table and the parseMessage function then parcels off each message to the right function on the class.
It's ugly and slow but it should work.
Second way of doing this:
Define the virtual functions further down the hierarchy so if you want to add int foo(bar*); you first add a class that defines it as virtual and then ensure every class that wants to define int foo(bar*); inherit from it. You can then use dynamic_cast to ensure that the pointer you are looking at inherits from this class before trying to call int foo(bar*);. Possible these interface adding classes could be pure virtual so they can be mixed in to various points using multiple inheritance, but that may have its own problems.
This is less flexible than the first way and requires the classes that implement a function to be linked to each other. Oh, and it's still ugly.
But mostly I suggest you try and write C++ code like C++ code not Objective-C code.
This can be solved by adding some sort of introspection capabilities and meta object system. This talk Metadata and reflection in C++ — Jeff Tucker demonstrates how to do this using c++'s template meta programming.
If you don't want to go to the trouble of implementing one yourself, then it would be easier to use an existing one such as Qt's meta object system. Note that this solution does not work with multiple inheritance due to limitations in the meta object compiler: QObject Multiple Inheritance.
With that installed, you can query for the presence of methods and call them. This is quite tedious to do by hand, so the easiest way to call such a methods is using the signal and slot mechanism.
There is also GObject which is quite simmilar and there are others.
If you are planning to create many different children classes in different files, perhaps made by different people, and also I would guess you don't want to change your main code for every child class. Then I think what you need to do in your base class is to define several (not to many) virtual functions (with empty implementation) BUT those functions should be used to mark a time in the logic where they are called like "AfterInseart" or "BeforeSorting", Etc.
Usually there are not to many places in the logic you wish a derived classes to perform there own logic.

What are the disadvantages of "upcasting"?

The purpose of an abstract class is not to let the developers create an object of the base class and then upcast it, AFAIK.
Now, even if the upcasting is not required, and I still use it, does it prove to be "disadvantageous" in some way?
More clarification:
From The Thinking in C++:
Often in a design, you want the base class to present only an
interface for its derived classes. That is, you don’t want anyone to
actually create an object of the base class, only to upcast to it so that
its interface can be used. This is accomplished by making that class
abstract,
By upcasting, I meant: baseClass *obj = new derived ();
Upcasting can be disadvantageous for non polymorphic classes. For example:
class Fruit { ... }; // doesn't contain any virtual method
class Apple : public Fruit { ... };
class Blackberry : public Fruit { ... };
upcast it somewhere,
Fruit *p = new Apple; // oops, information gone
Now, you will never know (without any manual mechanism) that if *p is an instance of an Apple or a Blackberry.
[Note that dynamic_cast<> is not allowed for non-polymorphic classes.]
Abstract classes are used to express concepts that are common to a set of (sub-)classes, but for which it is not sensible to create instances.
Consider a class Animal. It does not make sense to create an instance of that class, because there is no thing that is just an animal. There are ducks, dogs and elephants, each of which is a subclass of animal. By formally declaring the class animal you can capture the similarities of all types of animals, and by making it abstract you can express that it cannot be instantiated.
Upcasting is required to make use of polymorphism in statically typed languages. This is, as #Jigar Joshi pointed out in a comment, called the Liskov Substituion Principle.
Edit: Upcasting is not disadvantageous. In fact, you should use it whenever possible, making your code depend on super-classes(interfaces) instead of base-classes(implementations). This enables you later switch implementations without having to change your code.
Upcasting is a technical tool.
Like every tool it is useful when used correctly and dangerous / disadvantageous if used inconsistently.
It can be good or bad depending on how "pure" you want your code to be in respect to a given programming paradigm.
Now, C++ is not necessarily "pure OOP", not necessarily "pure Generic", not necessarily "pure functional". And since C++ is a "pragmatic language", it is not in general an advantage force it to fit a "one and only paradigm".
The only thing that can be said, in technical terms, is that,
A derived class is a base class plus something more
Referring a derived through a base pointer makes that "something more" not accessible, unless there is a mechanism in the base to make you jump into the derived scope.
The mechanism C++ offers for that implicit jump are virtual functions.
The mechanism C++ offers for explicit jump is dynamic_cast (used in downcasting).
For non-polymorphic objects (that don't have any virtual method) static_cast (to downcast) is still available, but with no runtime check.
Advantages and disadvantages derive from consistent and inconsistent use of all of those points together. Is not a matter related to downcast only.
One disadvantage would be the obvious loss of new functionality introduced in the derived class:
class A
{
void foo();
}
class B : public A
{
void foo2();
}
A* b = new B;
b->foo2(); //error - no longer visible
I'm talking here about non-virtual functions.
Also, if you forget to make your destructors virtual, you might get some memory leaks when deleting a derived object via a pointer to a base object.
However all these can be avoided with a good architecture.

Best way to organize a class hierarchy including an overridable "Update" function

I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update().
I have a class "Bar" derived from my base class, that also needs to update every frame.
I could give the derived class an Update() function, but then I would have to remember to call its base::Update() function - nothing enforces my requirement that the base::Update() function is called because I have overriden it, and could easily just forget to (or choose not to) call the base:Update function.
So as an alternative I could give the base class a protected OnUpdate() function, which could be made overrideable, and call it from the base::Update() function. This removes the onus on me to remember to call base::Update() from the derived update function because I'm no longer overriding it. A Bar instance called "bar" will have bar->Update() called on it; this will first call the base class' Update() method, which will in turn call the overriden OnUpdate() function, performing the derived class' necessary updates.
Which solves everything. Except. What if I want to derive yet another updatable class, this time from the "Bar" class.
Baz (which derives from Bar) also has update requirements. If I put them in Baz's OnUpdate() function, I'm back to the original problem in that I'd have to remember to tell Baz's OnUpdate() function to call Bar's OnUpdate() function, otherwise Bar's OnUpdate() function wouldn't get called.
So really, I'd want Bar's OnUpdate() function to be non-overridable, and instead for it to call an overridable function after it has done whatever it needed to do, perhaps called OnUpdate2()...
And if I wanted to derive yet another class? OnUpdate3? OnUpdate4? AfterUpdate?
Is there a Better Way?
Further Info:
My specific problem domain is a 3d world. I've decided my base class is a "Locator" (an object with a location and orientation).
My first derived class is a "PhysicsObject" - a Locator that also has mass, velocity, collision information, etc.
My next derived class is a "Camera" - which derives from PhysicsObject. As well as position, and velocity, it also has information about the viewport, depth of field, etc.
MattK suggests simplifying the hierarchy - if a Locator is never referred to, incorporate it into PhysicsObject.
I'm also thinking about how I would go about turning the layout upside down and using composition instead of inheritance.
Perhaps a Camera HAS physics properties.
Perhaps a PhysicsObject HAS a location.
I'll have to think some more about this problem.
I like Uri's approach: "Observe the contract." Here's the rule - please follow it. Uri is right in that whatever kind of safeguards I try to put in, anyone could circumvent them, so perhaps in this case, the simplest solution is best. All my update() functions are going to have the requirement of calling their base::update() function.
Thanks for the help everyone!
Sounds like you want composition instead of inheritance. What if there was an interface IUpdateable, and Foo held a collection of IUpdateable objects, and called an Update method on each one every tick? Then Bar and Baz could just implement Update; your only worry would be how best to register them with Foo.
Based on your further info: You might want to consider your main object being analagous to your PhysicsObject, and using composition to include objects that implement specific behaviors, such as those of the Camera object.
That's a great question, I've encountered it many many times.
Unfortunately, there are at present no language mechanisms that I am familiar with for mainstream languages like C++ to do that, though I expect (at least in the future) for Java to have something with annotations.
I've used a variety of techniques including what you've suggested, each with pros and cons. Convulted approaches are not always worth the cost.
My view today is that if you really need to use inheritance (rather than composition), as it sounds here, then it is better to go for the elegant solution and observe the written contract. I admit, it's dangerous, but there are risks to the other approaches as well.
Generally speaking people are more careful reading the documentation of an overridden method than they are of a method they are using. In other words, while you would want to avoid "surprising" the user of your class, and can't count on him reading docs, you can count a little more on that in the case of inheritance, especially if you are the only user.
If you are presenting an API function and you expect many other individuals to override your subclass, you could put all kinds of sanity checks to ensure that the method was called, but in the end, you have to rely on the contract, just as so many standard library classes do.
I think that what you want is not easily doable with a class hierarchy.
One possible solution is to use a library that handle signal/slots (I've use sigslot http://sigslot.sourceforge.net/).
In the base class you declare a signal.
class Base : has_slots<> {
public:
Base() { SignalUpdate.connect(this, &Base::OnUpdate); }
void Update() { SignalUpdate.emit(); }
void OnUpdate() { cout << "Base::OnUpdate" << endl; }
private:
signal0<> SignalUpdate;
};
Now on each "derived" class you connect such signal with you own method
class Derived : public Base {
public:
Derived() { SignalUpdate.connect(this, &Derived::OnDerivedUpdate); }
void OnDerivedUpdate() { cout << "Derived::OnDerivedUpdate" << endl; }
};
(Note that this class no longer need to be a derivated from Base).
Now each time Update is called all methods that are connected will be called.
There are other framework that implement a similar behavior: boost signals, qt slots, libsigc++. You should try to take a look at these an see if they fit your needs.