Can some members of a class be accessible only by base classes? - c++

I have a Widget class and a CompositeWidget that is derived from it. CompositeWidget adds child management behaviour. The Widget constructor takes a CompositeWidget* parameter as the widget parent. I need to use this parent pointer to access some functionality within the CompositeWidget. For example:
Widget::Widget(CompositeWidget* parent)
{
parent_->AddChild(*this);
}
This forces me to create a public method CompositeWidget::AddChild. Is is possible to keep this interface private to the class hierarchy (a little like a reverse-protected access - limited to base classes)? Am I making a design faux pas in thinking about the problem like this?
Edit: I am trying to avoid friendship (if it's possible in this case).

This forces me to create a public method
No, you could declare:
friend class Widget;
In the CompositeWidget declaration. However...
Am I making a design faux pas
Having a parent class method that references a derived class has a whiff of design flaw in it, perhaps, but I won't say it's categorically wrong.

Use the friend keyword.
class Widget { ... };
class CompositeWidget {
friend class Widget;
};
However, you can alternatively insert the virtual method AddChild on the Widget class.

Answer to your concrete question: declare Widget to be a friend of your CompositeWidget and make AddChild a private member.
Alternatively, move the child management to CompositeWidget. The Design Patterns book has an extended discussion on this in their section on the Composite Pattern:
The decision involves a trade-off between safety and transparency:
Defining the child management interface at the root of the class hierarchy gives you transparency, because you can treat all components uniformly. It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves.
Defining child management in the Composite class gives you safety, because any attempt to add or remove objects from leaves will be caught at compile-time in a statically typed language like C++. But you lose transparency, because leaves and composites have different interfaces.
We have emphasized transparency over safety in this pattern. If you
opt for safety, then at times you may lose type information and have
to convert a component into a composite. How can you do this without
resorting to a type-unsafe cast?
They go on to give a long code example, which essentially boils down to this design where the CompositeWidget contains the child management:
class Widget
{
public:
//
virtual Composite* GetComposite() { return 0; }
}
class CompositeWidget: public Widget
{
public:
void AddChild(Component*);
// ...
virtual Composite* GetComposite() { return this; }
};
class LeafWidget: public Widget
{
// no child management here
};
GetComposite lets you query a widget to see if it's a composite. You
can perform AddChild safely on the composite it returns.

Related

how to add a function to a lib class without overriding it

I've a case in which I need to add some functions to a game engine class I'm using for a VR project without overriding the class it self:
The engine class name is AnnwaynPlayer that contains many useful methods to control the player, now I'm in the networking phase so I need to add 2 extra methods to this lib class which are setActive() and setConnected(), what is the best way to do this ?
If you can't touch the class itself then you probably want to use inheritance. This is one of the main goals of object-oriented programming -- to be able to add/change the behavior of an existing class without altering it. So you want something like:
class MyAnnwaynPlayer : public AnnwaynPlayer {
public:
void setActive();
void setConnected();
// ...
}
Now, things will be fine if AnnwaynPlayer has a virtual destructor. If it doesn't and your MyAnnwaynPlayer class has a non-trivial destructor then you have to wary of using an instance of MyAnnwaynPlayer through a pointer (be it raw or smart) of base class AnnwaynPlayer. When a pointer of the type is deleted, it will not chain through a call to your MyAnnwaynPlayer destructor.
Also consider ADL if you only need access to the public API of the base class. It's safer than inheritance, because you don't necessarily know the right class to inherit from in cases where the implementation returns something ultimately unspecified (like an internal derived class).
In essence, this would look like this:
namespace AnnwaynNamespace {
void setActive(AnnwaynPlayer& p);
void setConnected(AnnwaynPlayer& p);
};
And you could call them without using those functions (or the namespace), because ADL.
void wherever(AnnwaynNamespace::AnnwaynPlayer& p) {
setActive(p);
}
So setActive, etc, become part of the actual public API of the class, without involving any inheritance.

Can someone explain the benefits of polymorphism?

So I understand pretty much how it works, but I just can't grasp what makes it useful. You still have to define all the separate functions, you still have to create an instance of each object, so why not just call the function from that object vs creating the object, creating a pointer to the parent object and passing the derived objects reference, just to call a function? I don't understand the benefits of taking this extra step.
Why do this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
Parent* bar = &foo;
bar->function();
return -3234324;
}
vs this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
foo.function();
return -3234324;
}
They do exactly the same thing right? Only one uses more memory and more confusion as far as I can tell.
Both your examples do the same thing but in different ways.
The first example calls function() by using Static binding while the second calls it using Dynamic Binding.
In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.
What is the advantage?
The advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:
The calling code which uses these classes, will be like:
Shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
basep[i] -> Draw ();
Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on, and they are stored in a array of pointers of the type of more generalized base class Shape.
This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer point to the new concrete class.
At the sametime the calling code can call appropriate methods of those classes because the Draw() method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.
The above is an good example of applying Open Closed Principle of the famous SOLID design principles.
Say you want someone to show up for work. You don't know whether they need to take a car, take a bus, walk, or what. You just want them to show up for work. With polymorphism, you just tell them to show up for work and they do. Without polymorphism, you have to figure out how they need to get to work and direct them to that process.
Now say some people start taking a Segway to work. Without polymorphism, every piece of code that tells someone to come to work has to learn this new way to get to work and how to figure out who gets to work that way and how to tell them to do it. With polymorphism, you put that code in one place, in the implementation of the Segway-rider, and all the code that tells people to go to work tells Segway-riders to take their Segways, even though it has no idea that this is what it's doing.
There are many real-world programming analogies. Say you need to tell someone that there's a problem they need to investigate. Their preferred contact mechanism might be email, or it might be an instant message. Maybe it's an SMS message. With a polymorphic notification method, you can add a new notification mechanism without having to change every bit of code that might ever need to use it.
polymorphism is great if you have a list/array of object which share a common ancestor and you wich to do some common thing with them, or you have an overridden method. The example I learnt the concept from, use shapes as and overriding the draw method. They all do different things, but they're all a 'shape' and can all be drawn. Your example doesn't really do anything useful to warrant using polymorphism
A good example of useful polymorphism is the .NET Stream class. It has many implementations such as "FileStream", "MemoryStream", "GZipStream", etcetera. An algorithm that uses "Stream" instead of "FileStream" can be reused on any of the other stream types with little or no modification.
There are countless examples of nice uses of polymorphism. Consider as an example a class that represents GUI widgets. The most base classs would have something like:
class BaseWidget
{
...
virtual void draw() = 0;
...
};
That is a pure virtual function. It means that ALL the class that inherit the Base will need to implement it. And ofcourse all widgets in a GUI need to draw themselves, right? So that's why you would need a base class with all of the functions that are common for all GUI widgets to be defined as pure virtuals because then in any child you will do like that:
class ChildWidget
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
class ChildWidget2
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
Then in your code you need not care about checking what kind of widget it is that you are drawing. The responsibility of knowing how to draw itself lies with the widget (the object) and not with you. So you can do something like that in your main loop:
for(int i = 0; i < numberOfWidgets; i++)
{
widgetsArray[i].draw();
}
And the above would draw all the widgets no matter if they are of ChildWidget1, ChildWidget2, TextBox, Button type.
Hope that it helps to understand the benefits of polymorphism a bit.
Reuse, generalisation and extensibility.
I may have an abstract class hierarchy like this: Vehicle > Car. I can then simply derive from Car to implement concrete types SaloonCar, CoupeCar etc. I implement common code in the abstract base classes. I may have also built some other code that is coupled with Car. My SaloonCar and CoupeCar are both Cars so I can pass them to this client code without alteration.
Now consider that I may have an interface; IInternalCombustionEngine and a class coupled with with this, say Garage (contrived I know, stay with me). I can implement this interface on classes defined in separate class hierarchies. E.G.
public abstract class Vehicle {..}
public abstract class Bus : Vehicle, IPassengerVehicle, IHydrogenPowerSource, IElectricMotor {..}
public abstract class Car : Vehicle {..}
public class FordCortina : Car, IInternalCombustionEngine, IPassengerVehicle {..}
public class FormulaOneCar : Car, IInternalCombustionEngine {..}
public abstract class PowerTool {..}
public class ChainSaw : PowerTool, IInternalCombustionEngine {..}
public class DomesticDrill : PowerTool, IElectricMotor {..}
So, I can now state that an object instance of FordCortina is a Vehicle, it's a Car, it's an IInternalCombustionEngine (ok contrived again, but you get the point) and it's also a passenger vehicle. This is a powerful construct.
The poly in polymorphic means more than one. In other words, polymorphism is not relevant unless there is more than one derived function.
In this example, I have two derived functions. One of them is selected based on the mode variable. Notice that the agnostic_function() doesn't know which one was selected. Nevertheless, it calls the correct version of function().
So the point of polymorphism is that most of your code doesn't need to know which derived class is being used. The specific selection of which class to instantiate can be localized to a single point in the code. This makes the code much cleaner and easier to develop and maintain.
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void function() const {};
};
class Derived1 : public Parent
{
void function() const { cout << "derived1"; }
};
class Derived2 : public Parent
{
void function() const { cout << "derived2"; }
};
void agnostic_function( Parent const & bar )
{
bar.function();
}
int main()
{
int mode = 1;
agnostic_function
(
(mode==1)
? static_cast<Parent const &>(Derived1())
: static_cast<Parent const &>(Derived2())
);
}
Polymorphism is One of the principles OOP. With polymorphism you can choose several behavior in runtime. In your sample, you have a implementation of Parent, if you have more implementation, you can choose one by parameters in runtime. polymorphism help for decoupling layers of application. in your sample of third part use this structers then it see Parent interface only and don't know implementation in runtime so third party independ of implementations of Parent interface. You can see Dependency Injection pattern also for better desing.
Just one more point to add. Polymorphism is required to implement run-time plug-ins. It is possible to add functionality to a program at run-time. In C++, the derived classes can be implemented as shared object libraries. The run time system can be programmed to look at a library directory, and if a new shared object appears, it links it in and can start to call it. This can also be done in Python.
Let's say that my School class has a educate() method. This method accepts only people who can learn. They have different styles of learning. Someone grasps, someone just mugs it up, etc.
Now lets say I have boys, girls, dogs, and cats around the School class. If School wants to educate them, I would have to write different methods for the different objects, under School.
Instead, the different people Objects (boys,girls , cats..) implement the Ilearnable interface. Then, the School class does not have to worry about what it has to educate.
School will just have to write a
public void Educate (ILearnable anyone)
method.
I have written cats and dogs because they might want to visit different type of school. As long as it is certain type of school (PetSchool : School) and they can Learn, they can be educated.
So it saves multiple methods that have the same implementation but different input types
The implementation matches the real life scenes and so it's easy for design purposes
We can concentrate on part of the class and ignore everything else.
Extension of the class (e.g. After years of education you come to know, hey, all those people around the School must go through GoGreen program where everyone must plant a tree in the same way. Here if you had a base class of all those people as abstract LivingBeings, we can add a method to call PlantTree and write code in PlantTree. Nobody needs to write code in their Class body as they inherit from the LivingBeings class, and just typecasting them to PlantTree will make sure they can plant trees).

Calling a Child class' method when processing a list of Parent class objects

This question seems like it might be somewhat common, but I didn't find anything when scowering StackOverflow or the interwebs.
I came across a method in a C++ class that takes a list of (for example) Parent objects. For this example, assume that there are two classes that derive from Parent: Child1 and Child2.
For each object in the list, the method checks if the object is of type Child2 (via a IsOfType() method that each class implements), and if so, it calls a method that is only provided by the Child2 class.
Is this an issue in that the list-processing method cannot treat each object the same? I've seen this done in other places as well, so it seems it might be a common practice to some degree.
One option might be to declare the Child2 method in the Parent class so that all Parent objects implement it. However, in this case, only the Child2 class would actually implement any behavior when overriding the method.
Your thoughts? Thanks in advance!
I think the following is a better solution for this problem.
class Parent {
public:
virtual int doSomething() {}
};
class Child1 : public Parent {
};
class Child2 : public Parent {
public:
virtual int doSomething();
Now you just omit the IsOfType call altogether and call doSomething on all of the pointers passed to you.
The only good reason I can think of as to why you'd have an IsOfType function is if you don't have control over the Parent class and can't modify it to add the doSomething method.
You could declare the new method in an interface that only Child2 implements. You could then use dynamic_cast<ISomeOtherInterface> to see if the object supports the extended feature. This cast will result in a null pointer for objects that don't support the additional interface.
This would allow you to create other objects that implement this feature, without requiring your list processing to know about each specific object type.
If your IsOfType() test passes, you can cast the (pointer to the) parent object to a Child2 object and access its specific member functions.
EDIT:
This depends on your design and on how strict you ensure the IsOfType() implementation will give correct answers (i.e. it also works when you add new subclasses in a week). It might be safer to make use of the builtin Typeid instead.
Implementing every possible method any child would ever have in the parent would be difficult, so upcasting is ok when the method is really semantically specific to the Child2 class.
You might find the Visitor Pattern useful in this instance. This will allow the objects themselves (child1, child2 etc) to call you back with their static type and take appropriate action.

Restrict method access to a specific class in C++

I have two closely related classes which I'll call Widget and Sprocket. Sprocket has a set of methods which I want to be callable from Widget but not from any other class. I also don't want to just declare Widget a friend of Spocket because that would give Widget access to ALL protected and private members. I want to restrict Widget's access to only a specific set of methods.
One solution I came up with is to create a nested class inside Sprocket that contains wrappers for these methods and make Widget a friend of this nested class. For example:
class Sprocket
{
public:
class WidgetInterface
{
friend class Widget;
WidgetInterface(Sprocket* parent) : mParent(parent) {}
private:
void A() { mParent->A(); }
void B() { mParent->B(); }
Sprocket* mParent;
};
private:
void A() { ... }
void B() { ... }
};
class Widget
{
public:
Widget(Sprocket* sprock) : mSprocketIface(sprock) {}
void doStuff() { mSprocketIface.A(); } // Widget can call Sprocket::A()
private:
Sprocket::WidgetInterface mSprocketIface;
};
This results in some code duplication because the method signatures are now declared in two places, but it works. But now suppose I want to add a subclass of Widget called SpecialWidget and I want that class to also have access to the Sprocket methods. I can simply add this new class to the Sprocket friends list or I can add yet another set of protected wrappers in Widget that SpecialWidget (and any other subclass) can access but you can see that this is now becoming a maintenance issue. I don't want to have to update the friends list or the wrappers if I add new classes or change the method signature. If I use the "add another set of wrappers" approach, the method signatures will be duplicated in three places!
Does anyone know of a simpler, cleaner way to do this?
If you have two tightly coupled classes, then it's really not worth trying to make friend access any more granular than it is. You control the implementation of both, and you should trust yourself enough to not abuse the ability to call some methods that you don't, strictly speaking, need to call.
If you want to make it clear for future code maintainers, add a comment to the friend declaration explaining why it is there (a good idea in general), and what private methods are allowed to be called by the friend class.
Sprocket has a set of methods which I want to be callable from Widget but not from any other class.
Why not save yourself some trouble & implement this set of methods in Widget, perhaps adding a Sprocket parameter to these methods?
I would have implemented WidgetInterface as a real interface inherited by Sprocket, so A and B are all that Widget know about. Okay, other can use that interface too, but they probably will have a reason for this.
The secret is all this access control is pointless and illusionary, and there's no way to really limit any access to anything. You are just complicating things and making it difficult to figure out what parts of widget are ok to use and what parts are not. Instead, make the interface for widget and sprocket more obvious, and perhaps have widget own a private sprocket. If people are so clueless that they will violate this there's no help for it, but if you make something abominable and hard to figure out it guarantees even people who know C++ well will be unable to easily make use of it.

How can I manage a group of derived but otherwise Unrelated Classes

It seems the more I talk about this problem the better I understand it. I think my previous question didn't convey what I am trying to do correctly. My apologies for that.
In my design I have GameObjects which are essentially an aggregation class, all functionality in a GameObject is implemented by adding various "Features" to it. A Feature is a Subclass of the Feature class that has it's own members and functions. All Features can receive Messages
class Feature
{
public:
virtual void takeMessage(Message& message) = 0;
};
class VisualFeature : public Feature
{
public:
void takeMessage(Message& message);
private:
RenderContext m_renderer;
};
... Additional Features ...
FeatureServers are objects that are responsible for coordinating the various Features. GameObjects can subscribe to FeatureServers to receive messages from them, and Features can Subscribe to GameObjects to handle the messages it is interested in.
So for example in this code:
GameObject Square;
VisualFeature* SquareSprite = new VisualFeature();
Square.subscribe(SquareSprite, "MESSAGE_RENDER");
Square.addFeature(SquareSprite);
m_VisualFeatureServer.subscribe(Square, "MESSAGE_RENDER");
The VisualFeatureServer sends the message tied to "MESSAGE_RENDER" which may look something like this
class Message
{
public:
std::string getID() {return m_id;}
bool isConsumed() {return m_consumed;}
void consume() {m_consumed = true;}
protected:
bool isConsumed;
std::string m_id;
}
class Message_Render : public Message
{
public:
Message_Render() : m_id("MESSAGE_RENDER"), m_consumed(false) {}
RenderTarget& getRenderTarget() {return m_target;}
private:
RenderTarget& m_target;
};
When the VisualFeatureServer sends the Message_Render class to the Square GameObject it then forwards it to any FeatureComponents that are subscribed to receive that particular message. In this case the VisualFeature class receives the Message_Render message. Here is where my problem is, the VisualFeature class is going to receive a Message& that it can tell is a Message_Render by it's ID, I want to be able to treat it as a Message_Render rather then a Message like so:
void VisualFeature::takeMessage(Message& message)
{
//Here's the problem, I need a pattern to handle this elegantly
derivedMessage = convertMessageToDerivedType(message);
this->handleDerivedMessageType(derivedMessage);
}
void VisualFeature::handleDerivedMessageType(Message_Render& message)
{
message.getRenderTarget().render(m_renderer);
message.consume();
}
Is there a way to elegantly deal with the takeMessage portion of this design?
The other answer was getting too bloated with edits, so I started a new one.
The casting you are doing in the receiveMessage() functions is definitely a code smell.
I think you need to use a combination of:
Abstract factory pattern to instantiate your objects (messages and components)
Observer pattern to respond to messages
The idea is that each component type will only subscribe to messages of its own type, and will therefore only receive messages intended for it. This should eliminate the need for casting.
The notifying object could, as an example, use a vector of notifier objects indexed by the message ID. The observing object (the derived component class) could subscribe to the particular notifier indexed by its own message ID.
Do you think this design pattern would help?
I'm not sure that I really understand your question, and I think you need to clarify what you are trying to achieve more.
Just a few other comments though.
I don't think public inheritance (as you have implemented) is the best design pattern to use here. The golden rule with public inheritance is that it should only be used if the derived class truly "is a" object of the base class.
One of the main benefits of using inheritance in C++ is to implement polymorphism where (for example) you have a list of pointers to Base objects and you invoke methods on those objects, and they are dispatched to the relevant VisualComponent and PhysicsComponent object methods as appropriate.
Since (in your words) they have "unrelated class interfaces", you won't get any of the benefits of polymorphism.
It sounds like you are really inheriting from the Base class to implement the Mixin pattern.
Maybe composition is the better approach, where you include a copy of the Base class (which you will have to rename) in the VisualComponent or PhysicsComponent class.
However, based on the following question:
If I only have a reference or pointer
to Base what design options do I have
to expose the interface of
VisualComponent or PhysicsComponent?
Isn't the GameObject class (which you are instantiating in main()) already doing this for you?
Edit:
Okay, I think I understand better now that the question has been edited.
But I need some way to store all of
the Components dynamically in the
GameObject but still be able to use
their individual interfaces.
The only easy way I can see this working is by creating a virtual method in Base which is overridden in each derived class and implements class specific behaviour. GameObject could simply store a container of Base pointers and invoke the virtual method(s) which will be dispatched to the derived classes.
I would also recommend making Render(), Move() and any non-virtual methods private so that the GameObject class can only access the public (virtual) methods. The helps keep the public interface clean.
I'm not sure if this helps.
Edit 2:
After further discussion in the comments, it sounds like the factory pattern or the abstract factory pattern is what you need.
Visitor Pattern. If I understand what you are asking.
Though really need to know more context!
Take a look at boost.signals
You can define a signal for each message type and allow features to add slots (receivers) to it, this may be their member-functions of any name, or any other callable things of a proper signature.