Public inheritance for all except one function - c++

Say I have the following classes:
class Car
{
...
public:
void drive(Direction direction);
void open_door();
void refuel();
double get_speed();
...
};
class SelfDrivingCar: public Car
{
CarDrivingProgram *driving_program;
...
};
class CarDrivingProgram
{
public:
virtual void drive_car(Car *car) = 0;
};
class ExampleCarDrivingProgram: public CarDrivingProgram
{
void drive_car(Car *car) override;
...
};
SelfDrivingCar is a Car in every way except the user is forbidden from manually driving it. Instead, CarDrivingProgram drives it via drive_car(...). Using public inheritance seems correct because most operations on a Car could also happen to a SelfDrivingCar. For example, the user might create an array of Cars and then refuel all the Cars in the array, some of which happen to be SelfDrivingCars.
However, using public inheritance exposes the drive(...) method, which the user should not call on a SelfDrivingCar.
One solution would be to make the drive(...) method private in SelfDrivingCar, but that's messy, requires all CarDrivingPrograms to be friends in order to access drive(...), and can be circumvented if the user casts a SelfDrivingCar to a Car and then calls drive(...) from the Car.
Another solution would be to keep a boolean flag that indicates whether a Car is currently allowed to be driven or not and printing an error if drive(...) is called when the flag is set to "false". For a SelfDrivingCar, this flag would be "false" for most of the time, and CarDrivingProgram would temporarily set this to "true" for the duration of drive_car(...). However, this catches mistakes at runtime rather than at compile time, and the user can still toggle the flag and drive a SelfDrivingCar manually if they really want to.
Using protected/private inheritance would be another solution, but that prevents the user from doing something like adding SelfDrivingCars to an array of Cars that are to be later refuelled (described earlier).
How do I cleanly forbid the user from calling drive() on a SelfDrivingCar, ideally catching things at compile thing?
For clarification: The SelfDrivingCar class still needs a drive(...) function or something like it because CarDrivingProgram needs a way to tell SelfDrivingCar the direction to drive in. CarDrivingPrograms can drive any Car, not just SelfDrivingCars. I want CarDrivingProgram to be able to drive SelfDrivingCars but for the user to be unable to. For example, the user could have an array of pairs of CarDrivingPrograms and Cars, and call carDrivingProgram[i]->drive_car(car[i]) for each pair. I could make all CarDrivingPrograms friends but that's messy.

You could do something like this:
class Car {
...
public:
void open_door();
void refuel();
double get_speed();
...
};
class NormalCar: public Car{
public:
void drive(Direction direction);
};
class SelfDrivingCar: public Car
{
CarDrivingProgram *driving_program;
...
};
This is a very clean way. When there are no reasons you can't introduce another class, this should be fine. You can still store them in an array and refuel them.
When SelfDrivingCar is a Car that can drive, you can make it a Car and call the function (like TheUndeadFish mentioned in his comment). But you can't make a SelfDrivingCar a NormalCar.

Related

How can I access a private (non-static) method in C++?

Currently I am working on a project where I want to control a model train for a nice showcase.
I have multiple locomotives which all have a unique address (just think of it as a UUID). Some locomotives have a headlight, some of them have a flashing light, some have both and some of them have none.
My base class is this:
class GenericLocomotive : public Nameable, public Describable {
private:
uint16_t address;
public:
GenericLocomotive(const char* name, const char* description, uint16_t address);
void setFunction(uint8_t command, bool val);
Now I want to have a different class which provides the functionality to enable and disable the headlight:
class HasHeadLight {
public:
void activateHeadlight();
void deactivateHeadlight();
}
My goal is to have a specific class for every locomotive (with different functionality) which looks something like this:
class <SpecificLocomotive> : public GenericLocomotive, public HasHeadlight, public HasFlashlight,... {
...
}
The problem is, that I must have access to the private field 'address' of my GenericLocomotive class and I also have to call the function setFunction(...) from my HasHeadlight class.
I am quite new to C++ and just found out about the concept of friend classes and methods, but I can not quite get it to work, because even with the declaration of the method setFunction(...) as a friend, I can not just call something like
this->setFunction(HEADLIGHT_COMMAND, true);
from my HasHeadlight-class, because the function is not declared in 'this'.
How can I access the method from my other class? Is this friend thing even needed or is there a completely different way to structure my C++ program?
You have misunderstood how class inheritance works:
Inheritance establishes an is-a relationship between a parent and a child. The is-a relationship is typically stated as as a specialization relationship, i.e., child is-a parent.
There are many ways you can tackle what you want to achieve here, but this is not it. You're on the right track as far as treating the different train components as separate objects, and one way to achieve that would be to instead make each component a member of the specialized locomotive:
class HeadLight {
public:
void activateHeadlight();
void deactivateHeadlight();
}
class SpecialLocomotive : public GenericLocomotive {
HeadLight mHeadlight;
Flashlight mFlashlight;
public:
SpecialLocomotive(const char* name, const char* description, uint16_t address)
: GenericLocomotive(name, description, address) {
setFunction(HEADLIGHT_COMMAND, true);
}
void toggleLight(bool on) {
if (on) {
mHeadlight.activateHeadlight();
} else {
mHeadlight.void deactivateHeadlight();
}
}
/* so on and so forth /*
}
There's not enough details to go further with it. If you need to call setFunction from within Headlight, I would consider that a poor design choice, but there are other ways.

Private Vector in Header file: How to Get and Set values

I'm trying to declare a vector containing user objects in the header file, but I'm unsure of how to use the setter and getter functions to push values objects back to the vector or call them again.
class userbase
{
public:
userbase();
virtual ~userbase();
//FUNCTION DECLARATIONS
void record_User(user);
void setUserVector(vector<user> const &newUser) {
//userbase_V = newUser;
userbase_V.push_back(newUser);
}
vector<user> const &getUservector() const {
return userbase_V;
}
protected:
private:
vector <user> userbase_V;
};
Getters/setters are quite often misunderstood. The aim of using such functions is encapsulation which means restricting access to your data or exposing certain functions.
The reason why we don't make private members public in the first place is because there are some operations that we don't want users of our class to perform.
Consider the following class:
class userbase
{
public:
vector<user> users;
};
Let's say the goal of the userbase class is to manage a loyal, unwavering list of followers of an application. And since users is a public member, we can do whatever we want with it:
class company
{
public:
void massacre()
{
m_userbase.users.clear(); // Aaaaahhh!!!
}
private:
userbase m_userbase;
};
What? Where did all our loyal, unwavering followers go? We can't just remove our users!
The company class has access to all of std::vector's functionality on m_userbase.users. But really, from userbase's point of view, we don't want the outside to access particular functions (in this case, clear() or erase()). We want to restrict what operations can be performed (modifiers) and what attributes can retrieved (accessors). That is, we want to encapsulate the users vector.
Making userbase a private member is the first step:
class userbase
{
private:
vector<user> users;
};
Now let's add some naive "encapsulation" to see if it solves our problem. (This is where a lot of misunderstanding stems from.)
Here's our new class:
class userbase
{
public:
void setUsers(vector<user> const& newUsers) {
users = newUsers;
}
vector<user> const& getUsers() const {
return users;
}
private:
vector<user> users;
}
Can the company still clear the users vector directly? Yes.
class company
{
public:
void massacre()
{
auto users = m_userbase.getUsers();
users.clear();
m_userbase.setUsers(users); // Aaaaahhh!!!
// or simply create a new vector with no data
m_userbase.setUsers(std::vector<user>{}); // Aaaaahhh!!!
}
private:
userbase m_userbase;
};
So simply providing getters/setters doesn't solve the issue.
The common approach is to instead approach it the other way around. Instead of asking "What don't I want the outside to do?", ask "What do I want to allow the outside to do?". This way, you can figure what sort of functionality to expose. This is part of designing a good API.
Maybe our API wants to be able to: add a user, get a user's name, and count the number of users. Then we would design a class like this:
class userbase
{
public:
/// modifiers:
// Add a user to the userbase.
void addUser(User const& user);
/// accessors:
// Returns the user's name given its index.
string getUserName(size_t index) const;
// Returns the number of users belonging to this userbase.
size_t numberOfUsers() const;
private:
vector<user> m_users;
};
The takeaway is: it's up to you to decide what "the outside" can or can't do with its members. You'll need to spend more time thinking and less time writing code, but this is normal.
Further reading:
Why use getter and setters? (A good read even though it's tagged with Java.)

Redundant code in composition class C++

I'm trying to pick up C++. Everything was going well until my 'practice' program hit I very minor snag. That snag, I believe, stems from a design issue.
Think of Blackjack(21). I made a few classes.
Card
Deck
Hand
Player
A Deck consists of - for simplicities sake - Has An array of cards.
-It can show all it cards
-It can shuffle
-It can remove cards
A Hand Is A Deck -with the benefit of
-It can calculate its hand value
-It can add Cards to the hand
Now to get to my issue - the Player design
-A Player Has A hand (private access)
My problem with player, is that hand has a method function called addCardToHand. I feel a sense of redundancy/bad design if I have to create a Player method called addCardToHand(Card c) in which calls and passes to the same method in hand.
or
declare Hand h as a public accessible member and in 'main()' do something like
Player p;
Card aCard;
p.h.addCard(aCard);
Any advice would be enlightening and highly appreciated. Keep in mind I am learning.
The best answer here is: it depends :) I'll try to clarify it a little, though.
The first question is: does the Player class have any inner logic? If it's a simple container for Hand, I'd simply write Player.GetHand().AddCard(), because there is no reason to duplicate the code inside Player.AddCard() method, and the problem is solved.
Let's suppose now, that there is a need for implementing additional logic for adding a card to Player's hand. That means, that additional code in Player class has to be called while adding a card to Hand. In such case, I see three possible solutions.
(Sources only for demonstration purposes, may not compile)
Restrict access to Hand, such that no one can retrieve it from Player. Player would have to implement methods like AddToHand, RemoveFromHand etc. Doable, but not comfortable to use.
class Player
{
private:
Hand hand;
public:
void AddToHand(Card & card)
{
hand.Add(card);
}
};
Use the observer pattern. When user (class user) calls Player.GetHand().AddCard(), Hand notifies Player, that data has changed and Player can act accordingly. You can achieve this quite easily using std::function from C++11 to implement events.
class Deck
{
private:
std::function<void(void)> cardsChanged;
public:
void Add(Card card)
{
// Add a card
if (!(cardsChanged._Empty()))
cardsChanged();
}
void SetCardsChangedHandler(std::function<void(void)> newHandler)
{
cardsChanged = newHandler;
}
};
// (...)
class Player
{
private:
Hand hand;
void CardsChanged() { ... }
(...)
public:
Player()
{
hand.SetCardsChangedHandler([&this]() { this.CardsChanged(); } );
}
};
Define IHand interface with all necessary interface methods. Hand should obviously implement IHand and Player.GetHand() should return IHand. The trick is, that the IHand returned by Player do not necessarily have to be a Hand instance, but instead it can be a decorator acting as a bridge between user and real Hand instance (see decorator pattern).
class IHand
{
public:
virtual void Add(Card card) = 0;
virtual void Remove(Card card) = 0;
};
class Hand : public IHand
{
// Implementations
}
class PlayersHand : public IHand
{
private:
Hand & hand;
Player & player;
public:
PlayersHand(Hand & newHand, Player & newPlayer)
{
hand = newHand;
player = newPlayer;
}
void Add(Card card)
{
hand.Add(card);
player.HandChanged();
}
// ...
};
class Player
{
private:
Hand hand;
PlayersHand * playersHand;
public:
Player()
{
playersHand = new PlayersHand(hand, this);
}
IHand GetHand()
{
return playersHand;
}
}
Personally, In the second case, I would choose the second solution - it's quite straightforward and easy to extend and reuse in case of further needs.
Function call forwarding is a common practice. You should think about it as adding some level of abstraction. This is not exactly doing the same thing again (which redundancy would mean), but implementing one method, using another one.
You can imagine some modifications in the future, like adding Player's cards cache, or some other stuff that need to be updated when user call addCardToHand. Where would you add the cache-updating code if you didn't implement the forwarding method?
Also note, that the "interface" of Player::addCardToHand doesn't need to be identical with Card::addCard i.e. arguments and returned value can be different in these functions. Maybe in this case it's not so important, but generally the forwarding function is the place where some translation between Player's interface and Hand's interface may be added.

C++ Help on refactoring a monster class

I have a C background and am a newb on C++. I have a basic design question. I have a class (I'll call it "chef" b/c the problem I have seems very analogous to this, both in terms of complexity and issues) that basically works like this
class chef
{
public:
void prep();
void cook();
void plate();
private:
char name;
char dish_responsible_for;
int shift_working;
etc...
}
in pseudo code, this gets implemented along the lines of:
int main{
chef my_chef;
kitchen_class kitchen;
for (day=0; day < 365; day++)
{
kitchen.opens();
....
my_chef.prep();
my_chef.cook();
my_chef.plate();
....
kitchen.closes();
}
}
The chef class here seems to be a monster class, and has the potential of becoming one. chef also seems to violate the single responsibility principle, so instead we should have something like:
class employee
{
protected:
char name;
int shift_working;
}
class kitchen_worker : employee
{
protected:
dish_responsible_for;
}
class cook_food : kitchen_worker
{
public:
void cook();
etc...
}
class prep_food : kitchen_worker
{
public:
void prep();
etc...
}
and
class plater : kitchen_worker
{
public:
void plate();
}
etc...
I'm admittedly still struggling with how to implement it at run time so that, if for example plater (or "chef in his capacity as plater") decides to go home midway through dinner service, then the chef has to work a new shift.
This seems to be related to a broader question I have that if the same person invariably does the prepping, cooking and plating in this example, what is the real practical advantage of having this hierarchy of classes to model what a single chef does? I guess that runs into the "fear of adding classes" thing, but at the same time, right now or in the foreseeable future I don't think maintaining the chef class in its entirety is terribly cumbersome. I also think that it's in a very real sense easier for a naive reader of the code to see the three different methods in the chef object and move on.
I understand it might threaten to become unwieldy when/if we add methods like "cut_onions()", "cut_carrots()", etc..., perhaps each with their own data, but it seems those can be dealt with by having making the prep() function, say, more modular. Moreover, it seems that the SRP taken to its logical conclusion would create a class "onion_cutters" "carrot_cutters" etc... and I still have a hard time seeing the value of that, given that somehow the program has to make sure that the same employee cuts the onions and the carrots which helps with keeping the state variable the same across methods (e.g., if the employee cuts his finger cutting onions he is no longer eligible to cut carrots), whereas in the monster object chef class it seems that all that gets taken care of.
Of course, I understand that this then becomes less about having a meaningful "object oriented design", but it seems to me that if we have to have separate objects for each of the chef's tasks (which seems unnatural, given that the same person is doing all three function) then that seems to prioritize software design over the conceptual model. I feel an object oriented design is helpful here if we want to have, say, "meat_chef" "sous_chef" "three_star_chef" that are likely different people. Moreover, related to the runtime problem is that there is an overhead in complexity it seems, under the strict application of the single responsibility principle, that has to make sure the underlying data that make up the base class employee get changed and that this change is reflected in subsequent time steps.
I'm therefore rather tempted to leave it more or less as is. If somebody could clarify why this would be a bad idea (and if you have suggestions on how best to proceed) I'd be most obliged.
To avoid abusing class heirarchies now and in future, you should really only use it when an is relationship is present. As yourself, "is cook_food a kitchen_worker". It obviously doesn't make sense in real life, and doesn't in code either. "cook_food" is an action, so it might make sense to create an action class, and subclass that instead.
Having a new class just to add new methods like cook() and prep() isn't really an improvement on the original problem anyway - since all you've done is wrapped the method inside a class. What you really wanted was to make an abstraction to do any of these actions - so back to the action class.
class action {
public:
virtual void perform_action()=0;
}
class cook_food : public action {
public:
virtual void perform_action() {
//do cooking;
}
}
A chef can then be given a list of actions to perform in the order you specify. Say for example, a queue.
class chef {
...
perform_actions(queue<action>& actions) {
for (action &a : actions) {
a.perform_action();
}
}
...
}
This is more commonly known as the Strategy Pattern. It promotes the open/closed principle, by allowing you to add new actions without modifying your existing classes.
An alternative approach you could use is a Template Method, where you specify a sequence of abstract steps, and use subclasses to implement the specific behaviour for each one.
class dish_maker {
protected:
virtual void prep() = 0;
virtual void cook() = 0;
virtual void plate() = 0;
public:
void make_dish() {
prep();
cook();
plate();
}
}
class onion_soup_dish_maker : public dish_maker {
protected:
virtual void prep() { ... }
virtual void cook() { ... }
virtual void plate() { ... }
}
Another closely related pattern which might be suitable for this is the Builder Pattern
These patterns can also reduce of the Sequential Coupling anti-pattern, as it's all too easy to forget to call some methods, or call them in the right order, particularly if you're doing it multiple times. You could also consider putting your kitchen.opens() and closes() into a similar template method, than you don't need to worry about closes() being called.
On creating individual classes for onion_cutter and carrot_cutter, this isn't really the logical conclusion of the SRP, but in fact a violation of it - because you're making classes which are responsible for cutting, and holding some information about what they're cutting. Both cutting onions and carrots can be abstracted into a single cutting action - and you can specify which object to cut, and add a redirection to each individual class if you need specific code for each object.
One step would be to create an abstraction to say something is cuttable. The is relationship for subclassing is candidate, since a carrot is cuttable.
class cuttable {
public:
virtual void cut()=0;
}
class carrot : public cuttable {
public:
virtual void cut() {
//specific code for cutting a carrot;
}
}
The cutting action can take a cuttable object and perform any common cutting action that's applicable to all cuttables, and can also apply the specific cut behaviour of each object.
class cutting_action : public action {
private:
cuttable* object;
public:
cutting_action(cuttable* obj) : object(obj) { }
virtual void perform_action() {
//common cutting code
object->cut(); //specific cutting code
}
}

supplying dependency through base class

I have a list of Parts and some of them need a pointer to an Engine, lets call them EngineParts. What I want is to find these EngineParts using RTTI and then give them the Engine.
The problem is how to design the EnginePart. I have two options here, described below, and I don't know which one to choose.
Option 1 is faster because it does not have a virtual function.
Option 2 is easier if I want to Clone() the object because without data it does not need a Clone() function.
Any thoughts? Maybe there is a third option?
Option 1:
class Part;
class EnginePart : public Part {
protected: Engine *engine
public: void SetEngine(Engine *e) {engine = e}
};
class Clutch : public EnginePart {
// code that uses this->engine
}
Option 2:
class Part;
class EnginePart : public Part {
public: virtual void SetEngine(Engine *e)=0;
};
class Clutch : public EnginePart {
private: Engine *engine;
public: void SetEngine(Engine *e) { engine = e; }
// code that uses this->engine
}
(Note that the actual situation is a bit more involved, I can't use a simple solution like creating a separate list for EngineParts)
Thanks
Virtual functions in modern compilers (from about the last 10 years) are very fast, especially for desktop machine targets, and that speed should not affect your design.
You still need a clone method regardless, if you want to copy from a pointer-/reference-to-base, as you must allow for (unknown at this time) derived classes to copy themselves, including implementation details like vtable pointers. (Though if you stick to one compiler/implementation, you can take shortcuts based on it, and just re-evaluate those every time you want to use another compiler or want to upgrade your compiler.)
That gets rid of all the criteria you've listed, so you're back to not knowing how to choose. But that's easy: choose the one that's simplest for you to do. (Which that is, I can't say based of this made-up example, but I suspect it's the first.)
Too bad that the reply stating that 'a part cannot hold the engine' is deleted because that was actually the solution.
Since not the complete Engine is needed, I found a third way:
class Part;
class EngineSettings {
private:
Engine *engine
friend class Engine;
void SetEngine(Engine *e) {engine = e}
public:
Value* GetSomeValue(params) { return engine->GetSomeValue(params); }
};
class Clutch : public Part, public EngineSettings {
// code that uses GetSomeValue(params) instead of engine->GetSomeValue(params)
}
Because GetSomeValue() needs a few params which Engine cannot know, there is no way it could "inject" this value like the engine pointer was injected in option 1 and 2. (Well.. unless I also provide a virtual GetParams()).
This hides the engine from the Clutch and gives me pretty much only one way to code it.